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