Skip to content

Commit c89c048

Browse files
committed
Optimize out some read operations from the quick deflate algorithm
1 parent 862005b commit c89c048

File tree

2 files changed

+21
-12
lines changed

2 files changed

+21
-12
lines changed

zlib-rs/src/deflate/algorithm/quick.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -93,23 +93,27 @@ pub fn deflate_quick(stream: &mut DeflateStream, flush: DeflateFlush) -> BlockSt
9393
}
9494
}
9595

96+
let lc: u8;
9697
if state.lookahead >= WANT_MIN_MATCH {
97-
let hash_head = StandardHashCalc::quick_insert_string(state, state.strstart);
98+
macro_rules! first_four_bytes {
99+
($slice:expr, $offset:expr) => {
100+
u32::from_le_bytes($slice[$offset..$offset + 4].try_into().unwrap())
101+
};
102+
}
103+
104+
let str_val = {
105+
let str_start = &state.window.filled()[state.strstart..];
106+
first_four_bytes!(str_start, 0)
107+
};
108+
let hash_head = StandardHashCalc::quick_insert_value(state, state.strstart, str_val);
98109
let dist = state.strstart as isize - hash_head as isize;
99110

100111
if dist <= state.max_dist() as isize && dist > 0 {
101-
let str_start = &state.window.filled()[state.strstart..];
102112
let match_start = &state.window.filled()[hash_head as usize..];
103113

104-
macro_rules! first_two_bytes {
105-
($slice:expr, $offset:expr) => {
106-
u16::from_le_bytes($slice[$offset..$offset + 2].try_into().unwrap())
107-
};
108-
}
109-
110-
if first_two_bytes!(str_start, 0) == first_two_bytes!(match_start, 0) {
114+
if str_val == first_four_bytes!(match_start, 0) {
111115
let mut match_len = crate::deflate::compare256::compare256_slice(
112-
&str_start[2..],
116+
&state.window.filled()[state.strstart + 2..],
113117
&match_start[2..],
114118
) + 2;
115119

@@ -133,9 +137,10 @@ pub fn deflate_quick(stream: &mut DeflateStream, flush: DeflateFlush) -> BlockSt
133137
}
134138
}
135139
}
140+
lc = str_val as u8;
141+
} else {
142+
lc = state.window.filled()[state.strstart];
136143
}
137-
138-
let lc = state.window.filled()[state.strstart];
139144
state.bit_writer.emit_lit(StaticTreeDesc::L.static_tree, lc);
140145
state.strstart += 1;
141146
state.lookahead -= 1;

zlib-rs/src/deflate/hash_calc.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ impl StandardHashCalc {
3838
let slice = &state.window.filled()[string + Self::HASH_CALC_OFFSET..];
3939
let val = u32::from_le_bytes(slice[..4].try_into().unwrap());
4040

41+
Self::quick_insert_value(state, string, val)
42+
}
43+
44+
pub fn quick_insert_value(state: &mut State, string: usize, val: u32) -> u16 {
4145
let hm = Self::update_hash(0, val) as usize;
4246

4347
let head = state.head.as_slice()[hm];

0 commit comments

Comments
 (0)