Debian Codegraph @

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