Debian Codegraph @

third_party/rust/zlib-rs/src/deflate/algorithm/rle.rs

raw
1 #![forbid(unsafe_code)]
2
3 use crate::{
4 deflate::{
5 compare256::compare256_rle_slice, fill_window, BlockState, DeflateStream, MIN_LOOKAHEAD,
6 STD_MAX_MATCH, STD_MIN_MATCH,
7 },
8 flush_block, DeflateFlush,
9 };
10
11 pub fn deflate_rle(stream: &mut DeflateStream, flush: DeflateFlush) -> BlockState {
12 let mut match_len = 0;
13 let mut bflush;
14
15 loop {
16 // Make sure that we always have enough lookahead, except
17 // at the end of the input file. We need STD_MAX_MATCH bytes
18 // for the next match, plus WANT_MIN_MATCH bytes to insert the
19 // string following the next match.
20 if stream.state.lookahead < MIN_LOOKAHEAD {
21 fill_window(stream);
22 if stream.state.lookahead < MIN_LOOKAHEAD && flush == DeflateFlush::NoFlush {
23 return BlockState::NeedMore;
24 }
25 if stream.state.lookahead == 0 {
26 break; /* flush the current block */
27 }
28 }
29
30 /* See how many times the previous byte repeats */
31 let state = &mut stream.state;
32 if state.lookahead >= STD_MIN_MATCH && state.strstart > 0 {
33 let scan = &state.window.filled()[state.strstart - 1..][..3 + 256];
34
35 {
36 if scan[0] == scan[1] && scan[1] == scan[2] {
37 match_len = compare256_rle_slice(scan[0], &scan[3..]) + 2;
38 match_len = Ord::min(match_len, state.lookahead);
39 match_len = Ord::min(match_len, STD_MAX_MATCH);
40 }
41 }
42
43 assert!(
44 state.strstart - 1 + match_len <= state.window_size - 1,
45 "wild scan"
46 );
47 }
48
49 /* Emit match if have run of STD_MIN_MATCH or longer, else emit literal */
50 if match_len >= STD_MIN_MATCH {
51 // check_match(s, s->strstart, s->strstart - 1, match_len);
52
53 bflush = state.tally_dist(1, match_len - STD_MIN_MATCH);
54
55 state.lookahead -= match_len;
56 state.strstart += match_len;
57 match_len = 0;
58 } else {
59 /* No match, output a literal byte */
60 let lc = state.window.filled()[state.strstart];
61 bflush = state.tally_lit(lc);
62 state.lookahead -= 1;
63 state.strstart += 1;
64 }
65
66 if bflush {
67 flush_block!(stream, false);
68 }
69 }
70
71 stream.state.insert = 0;
72
73 if flush == DeflateFlush::Finish {
74 flush_block!(stream, true);
75 return BlockState::FinishDone;
76 }
77
78 if !stream.state.sym_buf.is_empty() {
79 flush_block!(stream, false);
80 }
81
82 BlockState::BlockDone
83 }