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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use byteorder::{LE, WriteBytesExt};
use std::hash::Hasher;
use std::io::{self, Read, Write, Seek, SeekFrom, ErrorKind};
use std::mem;
use twox_hash::XxHash32;
use thiserror::Error;
use fehler::{throws};
use super::{MAGIC, INCOMPRESSIBLE, WINDOW_SIZE};
use super::header::{Flags, BlockDescriptor};
use crate::raw::{U32Table, compress2, EncoderTable};
#[derive(Error, Debug)]
pub enum CompressionError {
#[error("error reading from the input you gave me")]
ReadError(io::Error),
#[error("error writing to the output you gave me")]
WriteError(#[from] io::Error),
#[error("the block size you asked for is not supported")]
InvalidBlockSize,
}
type Error = CompressionError;
impl From<Error> for io::Error {
fn from(e: Error) -> io::Error {
io::Error::new(ErrorKind::Other, e)
}
}
pub struct CompressionSettings<'a> {
independent_blocks: bool,
block_checksums: bool,
content_checksum: bool,
block_size: usize,
dictionary: Option<&'a [u8]>,
dictionary_id: Option<u32>,
}
impl<'a> Default for CompressionSettings<'a> {
fn default() -> Self {
Self {
independent_blocks: true,
block_checksums: false,
content_checksum: true,
block_size: 4 * 1024 * 1024,
dictionary: None,
dictionary_id: None,
}
}
}
impl<'a> CompressionSettings<'a> {
pub fn independent_blocks(&mut self, v: bool) -> &mut Self {
self.independent_blocks = v;
self
}
pub fn block_checksums(&mut self, v: bool) -> &mut Self {
self.block_checksums = v;
self
}
pub fn content_checksum(&mut self, v: bool) -> &mut Self {
self.content_checksum = v;
self
}
pub fn block_size(&mut self, v: usize) -> &mut Self {
self.block_size = v;
self
}
pub fn dictionary(&mut self, id: u32, dict: &'a [u8]) -> &mut Self {
self.dictionary_id = Some(id);
self.dictionary = Some(dict);
self
}
pub fn dictionary_id_nonsense_override(&mut self, id: Option<u32>) -> &mut Self {
self.dictionary_id = id;
self
}
#[throws]
pub fn compress<R: Read, W: Write>(&self, reader: R, writer: W) {
self.compress_internal(reader, writer, None)?;
}
#[throws]
pub fn compress_with_size_unchecked<R: Read, W: Write>(&self, reader: R, writer: W, content_size: u64) {
self.compress_internal(reader, writer, Some(content_size))?;
}
#[throws]
pub fn compress_with_size<R: Read + Seek, W: Write>(&self, mut reader: R, writer: W) {
let start = reader.seek(SeekFrom::Current(0))?;
let end = reader.seek(SeekFrom::End(0))?;
reader.seek(SeekFrom::Start(start))?;
let length = end - start;
self.compress_internal(reader, writer, Some(length))?;
}
#[throws]
fn compress_internal<R: Read, W: Write>(&self, mut reader: R, mut writer: W, content_size: Option<u64>) {
let mut content_hasher = None;
let mut flags = Flags::empty();
if self.independent_blocks {
flags |= Flags::IndependentBlocks;
}
if self.block_checksums {
flags |= Flags::BlockChecksums;
}
if self.content_checksum {
flags |= Flags::ContentChecksum;
content_hasher = Some(XxHash32::with_seed(0));
}
if self.dictionary_id.is_some() {
flags |= Flags::DictionaryId;
}
if content_size.is_some() {
flags |= Flags::ContentSize;
}
let version = 1 << 6;
let flag_byte = version | flags.bits();
let bd_byte = BlockDescriptor::new(self.block_size).ok_or(Error::InvalidBlockSize)?.0;
let mut header = Vec::new();
header.write_u32::<LE>(MAGIC)?;
header.write_u8(flag_byte)?;
header.write_u8(bd_byte)?;
if let Some(content_size) = content_size {
header.write_u64::<LE>(content_size)?;
}
if let Some(id) = self.dictionary_id {
header.write_u32::<LE>(id)?;
}
let mut hasher = XxHash32::with_seed(0);
hasher.write(&header[4..]);
header.write_u8((hasher.finish() >> 8) as u8)?;
writer.write_all(&header)?;
let mut template_table = U32Table::default();
let mut block_initializer: &[u8] = &[];
if let Some(dict) = self.dictionary {
for window in dict.windows(mem::size_of::<usize>()).step_by(3) {
let offset = window.as_ptr() as usize - dict.as_ptr() as usize;
template_table.replace(dict, offset);
}
block_initializer = dict;
}
let mut in_buffer = Vec::with_capacity(self.block_size);
in_buffer.extend_from_slice(block_initializer);
let mut out_buffer = vec![0u8; self.block_size];
let mut table = template_table.clone();
loop {
let window_offset = in_buffer.len();
reader.by_ref().take(self.block_size as u64).read_to_end(&mut in_buffer).map_err(Error::ReadError)?;
let read_bytes = in_buffer.len() - window_offset;
if read_bytes == 0 {
break;
}
if let Some(x) = content_hasher.as_mut() {
x.write(&in_buffer[window_offset..]);
}
let mut cursor = NoPartialWrites(&mut out_buffer[..read_bytes]);
let write = match compress2(&in_buffer, window_offset, &mut table, &mut cursor) {
Ok(()) => {
let not_written_len = cursor.0.len();
let written_len = read_bytes - not_written_len;
writer.write_u32::<LE>(written_len as u32)?;
&out_buffer[..written_len]
}
Err(e) => {
assert!(e.kind() == ErrorKind::ConnectionAborted);
writer.write_u32::<LE>((read_bytes as u32) | INCOMPRESSIBLE)?;
&in_buffer[window_offset..]
}
};
writer.write_all(write)?;
if flags.contains(Flags::BlockChecksums) {
let mut block_hasher = XxHash32::with_seed(0);
block_hasher.write(write);
writer.write_u32::<LE>(block_hasher.finish() as u32)?;
}
if flags.contains(Flags::IndependentBlocks) {
in_buffer.clear();
in_buffer.extend_from_slice(block_initializer);
table = template_table.clone();
} else {
if in_buffer.len() > WINDOW_SIZE {
let how_much_to_forget = in_buffer.len() - WINDOW_SIZE;
table.offset(how_much_to_forget);
in_buffer.drain(..how_much_to_forget);
}
}
}
writer.write_u32::<LE>(0)?;
if let Some(x) = content_hasher {
writer.write_u32::<LE>(x.finish() as u32)?;
}
}
}
struct NoPartialWrites<'a>(&'a mut [u8]);
impl<'a> Write for NoPartialWrites<'a> {
#[inline]
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
if self.0.len() < data.len() {
return Err(ErrorKind::ConnectionAborted.into());
}
let amt = data.len();
let (a, b) = mem::replace(&mut self.0, &mut []).split_at_mut(data.len());
a.copy_from_slice(data);
self.0 = b;
Ok(amt)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}