Debian Codegraph @

debian/rust-vendor/zlib-rs/src/deflate/longest_match.rs

raw
1 use crate::deflate::{Pos, State, MIN_LOOKAHEAD, STD_MAX_MATCH, STD_MIN_MATCH};
2
3 const EARLY_EXIT_TRIGGER_LEVEL: i8 = 5;
4
5 /// Find the (length, offset) in the window of the longest match for the string
6 /// at offset cur_match
7 pub fn longest_match(state: &crate::deflate::State, cur_match: u16) -> (usize, u16) {
8 longest_match_help::<false>(state, cur_match)
9 }
10
11 pub fn longest_match_slow(state: &crate::deflate::State, cur_match: u16) -> (usize, u16) {
12 longest_match_help::<true>(state, cur_match)
13 }
14
15 fn longest_match_help<const SLOW: bool>(
16 state: &crate::deflate::State,
17 mut cur_match: u16,
18 ) -> (usize, u16) {
19 let mut match_start = state.match_start;
20
21 let strstart = state.strstart;
22 let wmask = state.w_mask();
23 let window = state.window.filled();
24 let scan = &window[strstart..];
25
26 // Elide bounds checks in the loop.
27 let prev = &state.prev.as_slice()[..=wmask];
28 let mut limit: Pos;
29 let limit_base: Pos;
30 let early_exit: bool;
31
32 let mut chain_length: u16;
33 let mut best_len: usize;
34
35 let lookahead = state.lookahead;
36 let mut match_offset = 0;
37
38 macro_rules! goto_next_in_chain {
39 () => {
40 chain_length -= 1;
41 if chain_length > 0 {
42 cur_match = prev[cur_match as usize & wmask];
43
44 if cur_match > limit {
45 continue;
46 }
47 }
48
49 return (best_len, match_start);
50 };
51 }
52
53 // The code is optimized for STD_MAX_MATCH-2 multiple of 16.
54 assert_eq!(STD_MAX_MATCH, 258, "Code too clever");
55
56 // length of the previous match (if any), hence <= STD_MAX_MATCH
57 best_len = if state.prev_length > 0 {
58 state.prev_length as usize
59 } else {
60 STD_MIN_MATCH - 1
61 };
62
63 // Calculate read offset which should only extend an extra byte to find the next best match length.
64 let mut offset = best_len - 1;
65 if best_len >= core::mem::size_of::<u32>() {
66 offset -= 2;
67 if best_len >= core::mem::size_of::<u64>() {
68 offset -= 4;
69 }
70 }
71
72 let mut mbase_start = window.as_ptr();
73 let mut mbase_end = window[offset..].as_ptr();
74
75 // Don't waste too much time by following a chain if we already have a good match
76 chain_length = state.max_chain_length;
77 if best_len >= state.good_match as usize {
78 chain_length >>= 2;
79 }
80 let nice_match = state.nice_match;
81
82 // Stop when cur_match becomes <= limit. To simplify the code,
83 // we prevent matches with the string of window index 0
84 limit = strstart.saturating_sub(state.max_dist()) as Pos;
85
86 // look for a better string offset
87 if SLOW {
88 limit_base = limit;
89
90 if best_len >= STD_MIN_MATCH {
91 /* We're continuing search (lazy evaluation). */
92 let mut pos: Pos;
93
94 // Find a most distant chain starting from scan with index=1 (index=0 corresponds
95 // to cur_match). We cannot use s->prev[strstart+1,...] immediately, because
96 // these strings are not yet inserted into the hash table.
97 let Some([_cur_match, scan1, scan2, scanrest @ ..]) = scan.get(..best_len + 1) else {
98 panic!("invalid scan");
99 };
100
101 let mut hash = 0;
102 hash = state.update_hash(hash, *scan1 as u32);
103 hash = state.update_hash(hash, *scan2 as u32);
104
105 for (i, b) in scanrest.iter().enumerate() {
106 hash = state.update_hash(hash, *b as u32);
107
108 /* If we're starting with best_len >= 3, we can use offset search. */
109 pos = state.head.as_slice()[hash as usize];
110 if pos < cur_match {
111 match_offset = (i + 1) as Pos;
112 cur_match = pos;
113 }
114 }
115
116 /* Update offset-dependent variables */
117 limit = limit_base + match_offset;
118 if cur_match <= limit {
119 return break_matching(state, best_len, match_start);
120 }
121
122 mbase_start = mbase_start.wrapping_sub(match_offset as usize);
123 mbase_end = mbase_end.wrapping_sub(match_offset as usize);
124 }
125
126 early_exit = false;
127 } else {
128 // must initialize this variable
129 limit_base = 0;
130 early_exit = state.level < EARLY_EXIT_TRIGGER_LEVEL;
131 }
132
133 let scan_start = window[strstart..].as_ptr();
134 let mut scan_end = window[strstart + offset..].as_ptr();
135
136 assert!(
137 strstart <= state.window_size.saturating_sub(MIN_LOOKAHEAD),
138 "need lookahead"
139 );
140
141 loop {
142 if cur_match as usize >= strstart {
143 break;
144 }
145
146 // Skip to next match if the match length cannot increase or if the match length is
147 // less than 2. Note that the checks below for insufficient lookahead only occur
148 // occasionally for performance reasons.
149 // Therefore uninitialized memory will be accessed and conditional jumps will be made
150 // that depend on those values. However the length of the match is limited to the
151 // lookahead, so the output of deflate is not affected by the uninitialized values.
152
153 /// # Safety
154 ///
155 /// The two pointers must be valid for reads of N bytes.
156 #[inline(always)]
157 unsafe fn memcmp_n_ptr<const N: usize>(src0: *const u8, src1: *const u8) -> bool {
158 unsafe {
159 let src0_cmp = core::ptr::read(src0 as *const [u8; N]);
160 let src1_cmp = core::ptr::read(src1 as *const [u8; N]);
161 src0_cmp == src1_cmp
162 }
163 }
164
165 /// # Safety
166 ///
167 /// scan_start and scan_end must be valid for reads of N bytes. mbase_end and mbase_start
168 /// must be valid for reads of N + cur_match bytes.
169 #[inline(always)]
170 unsafe fn is_match<const N: usize>(
171 cur_match: u16,
172 mbase_start: *const u8,
173 mbase_end: *const u8,
174 scan_start: *const u8,
175 scan_end: *const u8,
176 ) -> bool {
177 let be = mbase_end.wrapping_add(cur_match as usize);
178 let bs = mbase_start.wrapping_add(cur_match as usize);
179 unsafe { memcmp_n_ptr::<N>(be, scan_end) && memcmp_n_ptr::<N>(bs, scan_start) }
180 }
181
182 // first, do a quick check on the start and end bytes. Go to the next item in the chain if
183 // these bytes don't match.
184 // SAFETY: we read up to 8 bytes in this block.
185 // Note that scan_start >= mbase_start and scan_end >= mbase_end.
186 // the surrounding loop breaks before cur_match gets past strstart, which is bounded by
187 // `window_size - 258 + 3 + 1` (`window_size - MIN_LOOKAHEAD`).
188 //
189 // With 262 bytes of space at the end, and 8 byte reads of scan_start is always in-bounds.
190 //
191 // scan_end is a bit trickier: it reads at a bounded offset from scan_start:
192 //
193 // - >= 8: scan_end is bounded by `258 - (4 + 2 + 1)`, so an 8-byte read is in-bounds
194 // - >= 4: scan_end is bounded by `258 - (2 + 1)`, so a 4-byte read is in-bounds
195 // - >= 2: scan_end is bounded by `258 - 1`, so a 2-byte read is in-bounds
196 let mut len = 0;
197 unsafe {
198 if best_len < core::mem::size_of::<u64>() {
199 let scan_val = u64::from_ne_bytes(
200 core::slice::from_raw_parts(scan_start, 8)
201 .try_into()
202 .unwrap(),
203 );
204 loop {
205 let bs = mbase_start.wrapping_add(cur_match as usize);
206 let match_val =
207 u64::from_ne_bytes(core::slice::from_raw_parts(bs, 8).try_into().unwrap());
208 let cmp = scan_val ^ match_val;
209 if cmp == 0 {
210 // The first 8 bytes all matched. Additional scanning will be needed
211 // (the compare256 call below) to determine the full match length.
212 break;
213 }
214 // Compute the number of leading bytes that match.
215 let cmp_len = cmp.to_le().trailing_zeros() as usize / 8;
216 if cmp_len > best_len {
217 // The match is fully contained within the 8 bytes just compared,
218 // so we know the match length without needing to do the more
219 // expensive compare256 operation.
220 len = cmp_len;
221 break;
222 }
223 goto_next_in_chain!();
224 }
225 } else {
226 loop {
227 if is_match::<8>(cur_match, mbase_start, mbase_end, scan_start, scan_end) {
228 break;
229 }
230
231 goto_next_in_chain!();
232 }
233 }
234 }
235
236 // we know that there is at least some match. Now count how many bytes really match
237 if len == 0 {
238 len = {
239 // SAFETY: cur_match is bounded by window_size - MIN_LOOKAHEAD, where MIN_LOOKAHEAD
240 // is 258 + 3 + 1, so 258-byte reads of mbase_start are in-bounds.
241 let src1 = unsafe {
242 core::slice::from_raw_parts(
243 mbase_start.wrapping_add(cur_match as usize + 2),
244 256,
245 )
246 };
247
248 crate::deflate::compare256::compare256_slice(&scan[2..], src1) + 2
249 };
250 }
251
252 assert!(
253 scan.as_ptr() as usize + len <= window.as_ptr() as usize + (state.window_size - 1),
254 "wild scan"
255 );
256
257 if len > best_len {
258 match_start = cur_match - match_offset;
259
260 // Do not look for better matches if the current match reaches
261 // or exceeds the end of the input. See also #459.
262 if len >= lookahead {
263 return (lookahead, match_start);
264 }
265 best_len = len;
266 if best_len >= nice_match as usize {
267 return (best_len, match_start);
268 }
269
270 offset = best_len - 1;
271 if best_len >= core::mem::size_of::<u32>() {
272 offset -= 2;
273 if best_len >= core::mem::size_of::<u64>() {
274 offset -= 4;
275 }
276 }
277
278 scan_end = window[strstart + offset..].as_ptr();
279
280 // Look for a better string offset
281 if SLOW && len > STD_MIN_MATCH && match_start as usize + len < strstart {
282 let mut pos: Pos;
283 // uint32_t i, hash;
284 // unsigned char *scan_endstr;
285
286 /* Go back to offset 0 */
287 cur_match -= match_offset;
288 match_offset = 0;
289 let mut next_pos = cur_match;
290
291 for i in 0..=len - STD_MIN_MATCH {
292 pos = prev[(cur_match as usize + i) & wmask];
293 if pos < next_pos {
294 /* Hash chain is more distant, use it */
295 if pos <= limit_base + i as Pos {
296 return break_matching(state, best_len, match_start);
297 }
298 next_pos = pos;
299 match_offset = i as Pos;
300 }
301 }
302 /* Switch cur_match to next_pos chain */
303 cur_match = next_pos;
304
305 /* Try hash head at len-(STD_MIN_MATCH-1) position to see if we could get
306 * a better cur_match at the end of string. Using (STD_MIN_MATCH-1) lets
307 * us include one more byte into hash - the byte which will be checked
308 * in main loop now, and which allows to grow match by 1.
309 */
310 let [scan0, scan1, scan2, ..] = scan[len - (STD_MIN_MATCH + 1)..] else {
311 panic!("index out of bounds");
312 };
313
314 let mut hash = 0;
315 hash = state.update_hash(hash, scan0 as u32);
316 hash = state.update_hash(hash, scan1 as u32);
317 hash = state.update_hash(hash, scan2 as u32);
318
319 pos = state.head.as_slice()[hash as usize];
320 if pos < cur_match {
321 match_offset = (len - (STD_MIN_MATCH + 1)) as Pos;
322 if pos <= limit_base + match_offset {
323 return break_matching(state, best_len, match_start);
324 }
325 cur_match = pos;
326 }
327
328 /* Update offset-dependent variables */
329 limit = limit_base + match_offset;
330 mbase_start = window.as_ptr().wrapping_sub(match_offset as usize);
331 mbase_end = mbase_start.wrapping_add(offset);
332 continue;
333 }
334
335 mbase_end = mbase_start.wrapping_add(offset);
336 } else if !SLOW && early_exit {
337 // The probability of finding a match later if we here is pretty low, so for
338 // performance it's best to outright stop here for the lower compression levels
339 break;
340 }
341
342 goto_next_in_chain!();
343 }
344
345 (best_len, match_start)
346 }
347
348 fn break_matching(state: &State, best_len: usize, match_start: u16) -> (usize, u16) {
349 (Ord::min(best_len, state.lookahead), match_start)
350 }