Debian Codegraph @

debian/rust-vendor/zopfli/src/lz77.rs

raw
1 use alloc::{boxed::Box, vec::Vec};
2 use core::cmp;
3
4 use crate::{
5 cache::Cache,
6 hash::{Which, ZopfliHash},
7 symbols::{get_dist_symbol, get_length_symbol},
8 util::{
9 boxed_array, ZOPFLI_MAX_CHAIN_HITS, ZOPFLI_MAX_MATCH, ZOPFLI_MIN_MATCH, ZOPFLI_NUM_D,
10 ZOPFLI_NUM_LL, ZOPFLI_WINDOW_MASK, ZOPFLI_WINDOW_SIZE,
11 },
12 };
13
14 #[derive(Clone, Copy)]
15 pub enum LitLen {
16 Literal(u16),
17 LengthDist(u16, u16),
18 }
19
20 impl LitLen {
21 pub const fn size(&self) -> usize {
22 match *self {
23 Self::Literal(_) => 1,
24 Self::LengthDist(len, _) => len as usize,
25 }
26 }
27 }
28
29 /// Stores lit/length and dist pairs for LZ77.
30 /// Parameter litlens: Contains the literal symbols or length values.
31 /// Parameter dists: Contains the distances. A value is 0 to indicate that there is
32 /// no dist and the corresponding litlens value is a literal instead of a length.
33 /// Parameter size: The size of both the litlens and dists arrays.
34 #[derive(Clone, Default)]
35 pub struct Lz77Store {
36 pub litlens: Vec<LitLen>,
37
38 pub pos: Vec<usize>,
39
40 ll_symbol: Vec<u16>,
41 d_symbol: Vec<u16>,
42
43 ll_counts: Vec<usize>,
44 d_counts: Vec<usize>,
45 }
46
47 impl Lz77Store {
48 pub const fn new() -> Self {
49 Self {
50 litlens: vec![],
51
52 pos: vec![],
53
54 ll_symbol: vec![],
55 d_symbol: vec![],
56
57 ll_counts: vec![],
58 d_counts: vec![],
59 }
60 }
61
62 pub fn reset(&mut self) {
63 self.litlens.clear();
64 self.pos.clear();
65 self.ll_symbol.clear();
66 self.d_symbol.clear();
67 self.ll_counts.clear();
68 self.d_counts.clear();
69 }
70
71 pub fn size(&self) -> usize {
72 self.litlens.len()
73 }
74
75 pub fn append_store_item(&mut self, litlen: LitLen, pos: usize) {
76 let origsize = self.litlens.len();
77 let llstart = ZOPFLI_NUM_LL * (origsize / ZOPFLI_NUM_LL);
78 let dstart = ZOPFLI_NUM_D * (origsize / ZOPFLI_NUM_D);
79
80 if origsize % ZOPFLI_NUM_LL == 0 {
81 if origsize == 0 {
82 self.ll_counts.resize(origsize + ZOPFLI_NUM_LL, 0);
83 } else {
84 // Append last histogram
85 self.ll_counts
86 .extend_from_within((origsize - ZOPFLI_NUM_LL)..origsize);
87 }
88 }
89
90 if origsize % ZOPFLI_NUM_D == 0 {
91 if origsize == 0 {
92 self.d_counts.resize(ZOPFLI_NUM_D, 0);
93 } else {
94 // Append last histogram
95 self.d_counts
96 .extend_from_within((origsize - ZOPFLI_NUM_D)..origsize);
97 }
98 }
99
100 self.pos.push(pos);
101
102 // Why isn't this at the beginning of this function?
103 // assert(length < 259);
104
105 self.litlens.push(litlen);
106 match litlen {
107 LitLen::Literal(length) => {
108 self.ll_symbol.push(length);
109 self.d_symbol.push(0);
110 self.ll_counts[llstart + length as usize] += 1;
111 }
112 LitLen::LengthDist(length, dist) => {
113 let len_sym = get_length_symbol(length as usize);
114 self.ll_symbol.push(len_sym as u16);
115 self.d_symbol.push(get_dist_symbol(dist));
116 self.ll_counts[llstart + len_sym] += 1;
117 self.d_counts[dstart + get_dist_symbol(dist) as usize] += 1;
118 }
119 }
120 }
121
122 pub fn lit_len_dist(&mut self, length: u16, dist: u16, pos: usize) {
123 let litlen = if dist == 0 {
124 LitLen::Literal(length)
125 } else {
126 LitLen::LengthDist(length, dist)
127 };
128
129 self.append_store_item(litlen, pos);
130 }
131
132 /// Does LZ77 using an algorithm similar to gzip, with lazy matching, rather than
133 /// with the slow but better "squeeze" implementation.
134 /// The result is placed in the `Lz77Store`.
135 /// If instart is larger than 0, it uses values before instart as starting
136 /// dictionary.
137 pub fn greedy<C: Cache>(&mut self, lmc: &mut C, in_data: &[u8], instart: usize, inend: usize) {
138 if instart == inend {
139 return;
140 }
141 let windowstart = instart.saturating_sub(ZOPFLI_WINDOW_SIZE);
142 let mut h = ZopfliHash::new();
143
144 let arr = &in_data[..inend];
145 h.warmup(arr, windowstart, inend);
146
147 for i in windowstart..instart {
148 h.update(arr, i);
149 }
150
151 let mut i = instart;
152 let mut leng;
153 let mut dist;
154 let mut lengthscore;
155
156 /* Lazy matching. */
157 let mut prev_length = 0;
158 let mut prev_match = 0;
159 let mut prevlengthscore;
160 let mut match_available = false;
161 while i < inend {
162 h.update(arr, i);
163
164 let longest_match =
165 find_longest_match(lmc, &h, arr, i, inend, instart, ZOPFLI_MAX_MATCH, &mut None);
166 dist = longest_match.distance;
167 leng = longest_match.length;
168 lengthscore = get_length_score(i32::from(leng), i32::from(dist));
169
170 /* Lazy matching. */
171 prevlengthscore = get_length_score(prev_length as i32, prev_match as i32);
172 if match_available {
173 match_available = false;
174 if lengthscore > prevlengthscore + 1 {
175 self.lit_len_dist(u16::from(arr[i - 1]), 0, i - 1);
176 if (lengthscore as usize) >= ZOPFLI_MIN_MATCH
177 && (leng as usize) < ZOPFLI_MAX_MATCH
178 {
179 match_available = true;
180 prev_length = u32::from(leng);
181 prev_match = u32::from(dist);
182 i += 1;
183 continue;
184 }
185 } else {
186 /* Add previous to output. */
187 leng = prev_length as u16;
188 dist = prev_match as u16;
189 /* Add to output. */
190 verify_len_dist(arr, i - 1, dist, leng);
191 self.lit_len_dist(leng, dist, i - 1);
192 for _ in 2..leng {
193 debug_assert!(i < inend);
194 i += 1;
195 h.update(arr, i);
196 }
197 i += 1;
198 continue;
199 }
200 } else if (lengthscore as usize) >= ZOPFLI_MIN_MATCH
201 && (leng as usize) < ZOPFLI_MAX_MATCH
202 {
203 match_available = true;
204 prev_length = u32::from(leng);
205 prev_match = u32::from(dist);
206 i += 1;
207 continue;
208 }
209 /* End of lazy matching. */
210
211 /* Add to output. */
212 if (lengthscore as usize) >= ZOPFLI_MIN_MATCH {
213 verify_len_dist(arr, i, dist, leng);
214 self.lit_len_dist(leng, dist, i);
215 } else {
216 leng = 1;
217 self.lit_len_dist(u16::from(arr[i]), 0, i);
218 }
219 for _ in 1..leng {
220 debug_assert!(i < inend);
221 i += 1;
222 h.update(arr, i);
223 }
224 i += 1;
225 }
226 }
227
228 pub fn follow_path<C: Cache>(
229 &mut self,
230 in_data: &[u8],
231 instart: usize,
232 inend: usize,
233 path: Vec<u16>,
234 lmc: &mut C,
235 ) {
236 let windowstart = instart.saturating_sub(ZOPFLI_WINDOW_SIZE);
237
238 if instart == inend {
239 return;
240 }
241
242 let mut h = ZopfliHash::new();
243
244 let arr = &in_data[..inend];
245 h.warmup(arr, windowstart, inend);
246
247 for i in windowstart..instart {
248 h.update(arr, i);
249 }
250
251 let mut pos = instart;
252 for item in path.into_iter().rev() {
253 let mut length = item;
254 debug_assert!(pos < inend);
255
256 h.update(arr, pos);
257
258 // Add to output.
259 if length >= ZOPFLI_MIN_MATCH as u16 {
260 // Get the distance by recalculating longest match. The found length
261 // should match the length from the path.
262 let longest_match = find_longest_match(
263 lmc,
264 &h,
265 arr,
266 pos,
267 inend,
268 instart,
269 length as usize,
270 &mut None,
271 );
272 let dist = longest_match.distance;
273 let dummy_length = longest_match.length;
274 debug_assert!(!(dummy_length != length && length > 2 && dummy_length > 2));
275 verify_len_dist(arr, pos, dist, length);
276 self.lit_len_dist(length, dist, pos);
277 } else {
278 length = 1;
279 self.lit_len_dist(u16::from(arr[pos]), 0, pos);
280 }
281
282 debug_assert!(pos + (length as usize) <= inend);
283 for j in 1..(length as usize) {
284 h.update(arr, pos + j);
285 }
286
287 pos += length as usize;
288 }
289 }
290
291 fn get_histogram_at(
292 &self,
293 lpos: usize,
294 ) -> (Box<[usize; ZOPFLI_NUM_LL]>, Box<[usize; ZOPFLI_NUM_D]>) {
295 let mut ll = boxed_array(0);
296 let mut d = boxed_array(0);
297
298 /* The real histogram is created by using the histogram for this chunk, but
299 all superfluous values of this chunk subtracted. */
300 let llpos = ZOPFLI_NUM_LL * (lpos / ZOPFLI_NUM_LL);
301 let dpos = ZOPFLI_NUM_D * (lpos / ZOPFLI_NUM_D);
302
303 for (i, item) in ll.iter_mut().enumerate() {
304 *item = self.ll_counts[llpos + i];
305 }
306 let end = cmp::min(llpos + ZOPFLI_NUM_LL, self.size());
307 for i in (lpos + 1)..end {
308 ll[self.ll_symbol[i] as usize] -= 1;
309 }
310
311 for (i, item) in d.iter_mut().enumerate() {
312 *item = self.d_counts[dpos + i];
313 }
314 let end = cmp::min(dpos + ZOPFLI_NUM_D, self.size());
315 for i in (lpos + 1)..end {
316 if let LitLen::LengthDist(_, _) = self.litlens[i] {
317 d[self.d_symbol[i] as usize] -= 1;
318 }
319 }
320
321 (ll, d)
322 }
323
324 /// Gets the histogram of lit/len and dist symbols in the given range, using the
325 /// cumulative histograms, so faster than adding one by one for large range. Does
326 /// not add the one end symbol of value 256.
327 pub fn get_histogram(
328 &self,
329 lstart: usize,
330 lend: usize,
331 ) -> (Box<[usize; ZOPFLI_NUM_LL]>, Box<[usize; ZOPFLI_NUM_D]>) {
332 if lstart + ZOPFLI_NUM_LL * 3 > lend {
333 let mut ll_counts = boxed_array(0);
334 let mut d_counts = boxed_array(0);
335 for i in lstart..lend {
336 ll_counts[self.ll_symbol[i] as usize] += 1;
337 if let LitLen::LengthDist(_, _) = self.litlens[i] {
338 d_counts[self.d_symbol[i] as usize] += 1;
339 }
340 }
341 (ll_counts, d_counts)
342 } else {
343 /* Subtract the cumulative histograms at the end and the start to get the
344 histogram for this range. */
345 let (ll, d) = self.get_histogram_at(lend - 1);
346
347 if lstart > 0 {
348 let (ll2, d2) = self.get_histogram_at(lstart - 1);
349
350 (
351 ll.iter()
352 .zip(ll2.iter())
353 .map(|(&ll_item1, &ll_item2)| ll_item1 - ll_item2)
354 .collect::<Vec<_>>()
355 .try_into()
356 .unwrap(),
357 d.iter()
358 .zip(d2.iter())
359 .map(|(&d_item1, &d_item2)| d_item1 - d_item2)
360 .collect::<Vec<_>>()
361 .try_into()
362 .unwrap(),
363 )
364 } else {
365 (ll, d)
366 }
367 }
368 }
369
370 pub fn get_byte_range(&self, lstart: usize, lend: usize) -> usize {
371 if lstart == lend {
372 return 0;
373 }
374
375 let l = lend - 1;
376 self.pos[l] + self.litlens[l].size() - self.pos[lstart]
377 }
378 }
379
380 pub struct LongestMatch {
381 pub distance: u16,
382 pub length: u16,
383 pub from_cache: bool,
384 pub limit: usize,
385 }
386
387 impl LongestMatch {
388 pub const fn new(limit: usize) -> Self {
389 Self {
390 distance: 0,
391 length: 0,
392 from_cache: false,
393 limit,
394 }
395 }
396 }
397
398 /// Finds how long the match of `scan` and `match` is. Can be used to find how many
399 /// bytes starting from `scan`, and from `match`, are equal. Returns the last byte
400 /// after `scan`, which is still equal to the corresponding byte after `match`.
401 /// `scan` is the position to compare; `match` is the earlier position to compare.
402 /// `end` is the last possible byte, beyond which to stop looking.
403 fn get_match(scan_arr: &[u8], match_arr: &[u8]) -> usize {
404 let max_prefix_len = cmp::min(scan_arr.len(), match_arr.len()); // The prefix won't be longer than the shortest array
405 let mut i = 0;
406
407 // This is a fairly hot function, and Rust's LLVM backend cannot autovectorize
408 // a comparison loop over bytes yet. To make it faster, we bring back the
409 // "several bytes at a time" optimization present in the original Zopfli code,
410 // but with a twist: instead of working with up to 64 bits at a time, let's
411 // always do the bulk of the work 128 bits at a time, using Rust's `u128` type.
412 // On x64, LLVM optimizes this function excellently, using SSE SIMD instructions
413 // such as `pcmpeqb` and `pmovmskb`, and it's likely such gains also translate to
414 // other architectures with baseline SIMD support for 128 bit vectors. This is
415 // even faster than the original Zopfli C code, while being more portable!
416 //
417 // The second condition in the while loop is there to guard against overflow when
418 // adding CHUNK_SIZE to i, allowing the compiler to not emit bound checks panic code
419 const CHUNK_SIZE: usize = core::mem::size_of::<u128>();
420 while i + CHUNK_SIZE < max_prefix_len && i + CHUNK_SIZE <= usize::MAX - CHUNK_SIZE {
421 let scan_chunk = u128::from_le_bytes(scan_arr[i..i + CHUNK_SIZE].try_into().unwrap());
422 let match_chunk = u128::from_le_bytes(match_arr[i..i + CHUNK_SIZE].try_into().unwrap());
423
424 let bit_diff_mask = scan_chunk ^ match_chunk;
425 if bit_diff_mask != 0 {
426 // Different bit in chunk found. Note that due to chunks being loaded as
427 // little-endian for better performance on little-endian CPUs, the number
428 // of trailing zeros represents the position of the first differing bit
429 // accurate only up to the byte boundary. Precise bit offsets would
430 // require reading big-endian integers and counting the leading zeros
431 // instead
432 return i + bit_diff_mask.trailing_zeros() as usize / 8;
433 }
434
435 i += CHUNK_SIZE;
436 }
437
438 // Now handle up to 15 remaining bytes naively, one at a time. Any performance
439 // gains from smaller chunks are likely to be negligible
440 for j in i..max_prefix_len {
441 if scan_arr[j] != match_arr[j] {
442 return j; // Different byte found
443 }
444 }
445
446 // All compared bytes are equal, so the common prefix is as long as it can be
447 max_prefix_len
448 }
449
450 #[allow(clippy::too_many_arguments)]
451 pub fn find_longest_match<C: Cache>(
452 lmc: &mut C,
453 h: &ZopfliHash,
454 array: &[u8],
455 pos: usize,
456 size: usize,
457 blockstart: usize,
458 limit: usize,
459 sublen: &mut Option<&mut [u16]>,
460 ) -> LongestMatch {
461 let mut longest_match = lmc.try_get(pos, limit, sublen, blockstart);
462
463 if longest_match.from_cache {
464 debug_assert!(pos + (longest_match.length as usize) <= size);
465 return longest_match;
466 }
467
468 let mut limit = longest_match.limit;
469
470 debug_assert!(limit <= ZOPFLI_MAX_MATCH);
471 debug_assert!(limit >= ZOPFLI_MIN_MATCH);
472 debug_assert!(pos < size);
473
474 if size - pos < ZOPFLI_MIN_MATCH {
475 /* The rest of the code assumes there are at least ZOPFLI_MIN_MATCH bytes to
476 try. */
477 longest_match.distance = 0;
478 longest_match.length = 0;
479 longest_match.from_cache = false;
480 longest_match.limit = 0;
481 return longest_match;
482 }
483
484 if pos + limit > size {
485 limit = size - pos;
486 }
487
488 let (bestdist, bestlength) = find_longest_match_loop(h, array, pos, size, limit, sublen);
489
490 lmc.store(pos, limit, sublen, bestdist, bestlength, blockstart);
491
492 debug_assert!(bestlength <= limit as u16);
493
494 debug_assert!(pos + bestlength as usize <= size);
495 longest_match.distance = bestdist;
496 longest_match.length = bestlength;
497 longest_match.from_cache = false;
498 longest_match.limit = limit;
499 longest_match
500 }
501
502 fn find_longest_match_loop(
503 h: &ZopfliHash,
504 array: &[u8],
505 pos: usize,
506 size: usize,
507 limit: usize,
508 sublen: &mut Option<&mut [u16]>,
509 ) -> (u16, u16) {
510 let mut which_hash = Which::Hash1;
511 let hpos = pos & ZOPFLI_WINDOW_MASK;
512
513 let mut pp = hpos; /* During the whole loop, p == hprev[pp]. */
514 let mut p = h.prev_at(pp, which_hash);
515
516 let mut dist = if p < pp {
517 pp - p
518 } else {
519 ZOPFLI_WINDOW_SIZE - p + pp
520 };
521
522 let mut bestlength = 1;
523 let mut bestdist = 0;
524 let mut chain_counter = ZOPFLI_MAX_CHAIN_HITS; /* For quitting early. */
525 let arrayend = pos + limit;
526 let mut scan_offset;
527 let mut match_offset;
528
529 /* Go through all distances. */
530 while dist < ZOPFLI_WINDOW_SIZE && chain_counter > 0 {
531 let mut currentlength = 0;
532
533 debug_assert!(p < ZOPFLI_WINDOW_SIZE);
534 debug_assert_eq!(p, h.prev_at(pp, which_hash));
535 debug_assert_eq!(h.hash_val_at(p, which_hash), i32::from(h.val(which_hash)));
536
537 if dist > 0 {
538 debug_assert!(pos < size);
539 debug_assert!(dist <= pos);
540 scan_offset = pos;
541 match_offset = pos - dist;
542
543 /* Testing the byte at position bestlength first, goes slightly faster. */
544 if pos + bestlength >= size
545 || array[scan_offset + bestlength] == array[match_offset + bestlength]
546 {
547 let same0 = h.same[pos & ZOPFLI_WINDOW_MASK];
548 if same0 > 2 && array[scan_offset] == array[match_offset] {
549 let same1 = h.same[(pos - dist) & ZOPFLI_WINDOW_MASK];
550 let same = cmp::min(cmp::min(same0, same1), limit as u16) as usize;
551 scan_offset += same;
552 match_offset += same;
553 }
554 scan_offset = get_match(
555 &array[scan_offset..arrayend],
556 &array[match_offset..arrayend],
557 ) + scan_offset;
558 currentlength = scan_offset - pos; /* The found length. */
559 }
560
561 if currentlength > bestlength {
562 if let Some(ref mut subl) = *sublen {
563 for sublength in subl.iter_mut().take(currentlength + 1).skip(bestlength + 1) {
564 *sublength = dist as u16;
565 }
566 }
567 bestdist = dist;
568 bestlength = currentlength;
569 if currentlength >= limit {
570 break;
571 }
572 }
573 }
574
575 /* Switch to the other hash once this will be more efficient. */
576 if which_hash == Which::Hash1
577 && bestlength >= h.same[hpos] as usize
578 && i32::from(h.val(Which::Hash2)) == h.hash_val_at(p, Which::Hash2)
579 {
580 /* Now use the hash that encodes the length and first byte. */
581 which_hash = Which::Hash2;
582 }
583
584 pp = p;
585 p = h.prev_at(p, which_hash);
586 if p == pp {
587 break; /* Uninited prev value. */
588 }
589
590 dist += if p < pp {
591 pp - p
592 } else {
593 ZOPFLI_WINDOW_SIZE - p + pp
594 };
595
596 chain_counter -= 1;
597 }
598 (bestdist as u16, bestlength as u16)
599 }
600
601 /// Gets a score of the length given the distance. Typically, the score of the
602 /// length is the length itself, but if the distance is very long, decrease the
603 /// score of the length a bit to make up for the fact that long distances use large
604 /// amounts of extra bits.
605 ///
606 /// This is not an accurate score, it is a heuristic only for the greedy LZ77
607 /// implementation. More accurate cost models are employed later. Making this
608 /// heuristic more accurate may hurt rather than improve compression.
609 ///
610 /// The two direct uses of this heuristic are:
611 /// -avoid using a length of 3 in combination with a long distance. This only has
612 /// an effect if length == 3.
613 /// -make a slightly better choice between the two options of the lazy matching.
614 ///
615 /// Indirectly, this affects:
616 /// -the block split points if the default of block splitting first is used, in a
617 /// rather unpredictable way
618 /// -the first zopfli run, so it affects the chance of the first run being closer
619 /// to the optimal output
620 const fn get_length_score(length: i32, distance: i32) -> i32 {
621 // At 1024, the distance uses 9+ extra bits and this seems to be the sweet spot
622 // on tested files.
623 if distance > 1024 {
624 length - 1
625 } else {
626 length
627 }
628 }
629
630 #[cfg(debug_assertions)]
631 fn verify_len_dist(data: &[u8], pos: usize, dist: u16, length: u16) {
632 for i in 0..length {
633 let d1 = data[pos - (dist as usize) + (i as usize)];
634 let d2 = data[pos + (i as usize)];
635 if d1 != d2 {
636 assert_eq!(d1, d2);
637 break;
638 }
639 }
640 }
641
642 #[cfg(not(debug_assertions))]
643 fn verify_len_dist(_data: &[u8], _pos: usize, _dist: u16, _length: u16) {}