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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#![forbid(unsafe_code)]
use super::flush_block;
use crate::deflate::hash_calc::StandardHashCalc;
use crate::{
deflate::{
fill_window, BlockState, DeflateStream, State, MIN_LOOKAHEAD, STD_MIN_MATCH, WANT_MIN_MATCH,
},
DeflateFlush,
};
pub fn deflate_medium(stream: &mut DeflateStream, flush: DeflateFlush) -> BlockState {
let mut state = &mut stream.state;
// For levels below 5, don't check the next position for a better match
let early_exit = state.level < 5;
let mut current_match = Match {
match_start: 0,
match_length: 0,
strstart: 0,
orgstart: 0,
};
let mut next_match = Match {
match_start: 0,
match_length: 0,
strstart: 0,
orgstart: 0,
};
loop {
let mut hash_head;
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need STD_MAX_MATCH bytes
* for the next match, plus WANT_MIN_MATCH bytes to insert the
* string following the next match.
*/
if stream.state.lookahead < MIN_LOOKAHEAD {
fill_window(stream);
if stream.state.lookahead < MIN_LOOKAHEAD && flush == DeflateFlush::NoFlush {
return BlockState::NeedMore;
}
if stream.state.lookahead == 0 {
break; /* flush the current block */
}
next_match.match_length = 0;
}
state = &mut stream.state;
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
/* If we already have a future match from a previous round, just use that */
if !early_exit && next_match.match_length > 0 {
current_match = next_match;
next_match.match_length = 0;
} else {
hash_head = 0;
if state.lookahead >= WANT_MIN_MATCH {
hash_head = StandardHashCalc::quick_insert_string(state, state.strstart);
}
current_match.strstart = state.strstart as u16;
current_match.orgstart = current_match.strstart;
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < WANT_MIN_MATCH
*/
let dist = state.strstart as i64 - hash_head as i64;
if dist <= state.max_dist() as i64 && dist > 0 && hash_head != 0 {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
let (match_length, match_start) =
crate::deflate::longest_match::longest_match(state, hash_head);
state.match_start = match_start;
current_match.match_length = match_length as u16;
current_match.match_start = match_start;
if (current_match.match_length as usize) < WANT_MIN_MATCH {
current_match.match_length = 1;
}
if current_match.match_start >= current_match.strstart {
/* this can happen due to some restarts */
current_match.match_length = 1;
}
} else {
/* Set up the match to be a 1 byte literal */
current_match.match_start = 0;
current_match.match_length = 1;
}
}
insert_match(state, current_match);
/* now, look ahead one */
// `window.filled().len() == window_size` (both are `2 * w_size`); comparing against
// the slice's own length lets LLVM drop the bounds checks of the insert below.
if !early_exit
&& state.lookahead > MIN_LOOKAHEAD
&& ((current_match.strstart + current_match.match_length) as usize)
< (state.window.filled().len() - MIN_LOOKAHEAD)
{
state.strstart = (current_match.strstart + current_match.match_length) as usize;
hash_head = StandardHashCalc::quick_insert_string(state, state.strstart);
next_match.strstart = state.strstart as u16;
next_match.orgstart = next_match.strstart;
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < WANT_MIN_MATCH
*/
let dist = state.strstart as i64 - hash_head as i64;
if dist <= state.max_dist() as i64 && dist > 0 && hash_head != 0 {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
let (match_length, match_start) =
crate::deflate::longest_match::longest_match(state, hash_head);
state.match_start = match_start;
next_match.match_length = match_length as u16;
next_match.match_start = match_start;
if next_match.match_start >= next_match.strstart {
/* this can happen due to some restarts */
next_match.match_length = 1;
}
if (next_match.match_length as usize) < WANT_MIN_MATCH {
next_match.match_length = 1;
} else {
fizzle_matches(
state.window.filled(),
state.max_dist(),
&mut current_match,
&mut next_match,
);
}
} else {
/* Set up the match to be a 1 byte literal */
next_match.match_start = 0;
next_match.match_length = 1;
}
state.strstart = current_match.strstart as usize;
} else {
next_match.match_length = 0;
}
/* now emit the current match */
let bflush = emit_match(state, current_match);
/* move the "cursor" forward */
state.strstart += current_match.match_length as usize;
if bflush {
flush_block!(stream, false);
}
}
stream.state.insert = Ord::min(stream.state.strstart, STD_MIN_MATCH - 1);
if flush == DeflateFlush::Finish {
flush_block!(stream, true);
return BlockState::FinishDone;
}
if !stream.state.sym_buf.is_empty() {
flush_block!(stream, false);
}
BlockState::BlockDone
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct Match {
match_start: u16,
match_length: u16,
strstart: u16,
orgstart: u16,
}
fn emit_match(state: &mut State, m: Match) -> bool {
let mut bflush = false;
/* matches that are not long enough we need to emit as literals */
if (m.match_length as usize) < WANT_MIN_MATCH {
for lc in &state.window.filled()[state.strstart..][..m.match_length as usize] {
bflush |= State::tally_lit_help(&mut state.sym_buf, &mut state.l_desc, *lc);
}
} else {
// check_match(s, m.strstart, m.match_start, m.match_length);
// `1 <= dist <= max_dist < 2^15` and `match_length <= STD_MAX_MATCH`, so both masks are
// the identity; they let LLVM prove the `d_code` and `LENGTH_CODE` lookups in range.
let dist = (((m.strstart - m.match_start) as usize).wrapping_sub(1) & 0x7FFF) + 1;
let len = (m.match_length as usize - STD_MIN_MATCH) & 0xFF;
bflush |= state.tally_dist(dist, len);
}
state.lookahead -= m.match_length as usize;
bflush
}
#[inline(always)]
fn insert_match(state: &mut State, mut m: Match) {
if state.lookahead <= (m.match_length as usize + WANT_MIN_MATCH) {
return;
}
/* matches that are not long enough we need to emit as literals */
if (m.match_length as usize) < WANT_MIN_MATCH {
m.strstart += 1;
m.match_length -= 1;
if m.match_length > 0 && m.strstart >= m.orgstart {
if m.strstart + m.match_length > m.orgstart {
state.insert_string(m.strstart as usize, m.match_length as usize);
} else {
state.insert_string(m.strstart as usize, (m.orgstart - m.strstart + 1) as usize);
}
}
return;
}
// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
if usize::from(m.match_length) <= 16 * state.max_insert_length()
&& state.lookahead >= WANT_MIN_MATCH
{
m.match_length -= 1; /* string at strstart already in table */
m.strstart += 1;
if m.strstart >= m.orgstart {
if m.strstart + m.match_length > m.orgstart {
state.insert_string(m.strstart as usize, m.match_length as usize);
} else {
state.insert_string(m.strstart as usize, (m.orgstart - m.strstart + 1) as usize);
}
} else if m.orgstart < m.strstart + m.match_length {
state.insert_string(
m.orgstart as usize,
(m.strstart + m.match_length - m.orgstart) as usize,
);
}
} else {
m.strstart += m.match_length;
m.match_length = 0;
if (m.strstart as usize) >= (STD_MIN_MATCH - 2) {
StandardHashCalc::quick_insert_string(state, m.strstart as usize + 2 - STD_MIN_MATCH);
}
/* If lookahead < WANT_MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
}
fn fizzle_matches(window: &[u8], max_dist: usize, current: &mut Match, next: &mut Match) {
/* step zero: sanity checks */
if current.match_length <= 1 {
return;
}
if current.match_length > 1 + next.match_start {
return;
}
if current.match_length > 1 + next.strstart {
return;
}
// Both offsets are non-negative after the checks above. Only the first byte of each is
// read, so fetch those bytes directly instead of building two tail slices.
let m = (next.match_start as usize + 1) - current.match_length as usize;
let orig = (next.strstart as usize + 1) - current.match_length as usize;
/* quick exit check.. if this fails then don't bother with anything else */
if window[m] != window[orig] {
return;
}
/* step one: try to move the "next" match to the left as much as possible */
let limit = next.strstart.saturating_sub(max_dist as u16);
let mut c = *current;
let mut n = *next;
let m = &window[..n.match_start as usize];
let orig = &window[..n.strstart as usize];
let mut m = m.iter().rev();
let mut orig = orig.iter().rev();
let mut changed = 0;
while m.next() == orig.next() {
if c.match_length < 1 {
break;
}
if n.strstart <= limit {
break;
}
if n.match_length >= 256 {
break;
}
if n.match_start <= 1 {
break;
}
n.strstart -= 1;
n.match_start -= 1;
n.match_length += 1;
c.match_length -= 1;
changed += 1;
}
if changed == 0 {
return;
}
if c.match_length <= 1 && n.match_length != 2 {
n.orgstart += 1;
*current = c;
*next = n;
}
}