| 1 |
use super::huffman::HuffmanDecoder; |
| 2 |
use bitstream_io::{BitRead, BitReader, Endianness, LittleEndian}; |
| 3 |
use std::io::{self, Cursor, Error, Read, Result}; |
| 4 |
|
| 5 |
/// Maximum symbol value in the length Huffman table (6 bits) |
| 6 |
/// When this value is decoded, an additional byte is read for extended length |
| 7 |
const MAX_LEN_SYMBOL: u16 = 63; |
| 8 |
|
| 9 |
/// Maximum number of symbols in a Huffman table (256 for literals, 64 for lengths/distances) |
| 10 |
const MAX_HUFFMAN_SYMBOLS: usize = 1 << 8; // 256 |
| 11 |
|
| 12 |
/// Maximum code length in bits for Huffman codes (per ZIP specification) |
| 13 |
const MAX_CODE_LENGTH: usize = 16; |
| 14 |
|
| 15 |
/// Size of the code length count array (lengths are actually 1..=16) |
| 16 |
const CODE_LENGTH_COUNT_SIZE: usize = MAX_CODE_LENGTH; |
| 17 |
|
| 18 |
/// Initialize the Huffman decoder d with num_lens codeword lengths read from is. |
| 19 |
/// Returns false if the input is invalid. |
| 20 |
fn read_huffman_code<T: std::io::Read, E: Endianness>( |
| 21 |
is: &mut BitReader<T, E>, |
| 22 |
num_lens: usize, |
| 23 |
) -> std::io::Result<Box<HuffmanDecoder>> { |
| 24 |
let mut lens = [0; MAX_HUFFMAN_SYMBOLS]; |
| 25 |
let mut len_count = [0; CODE_LENGTH_COUNT_SIZE]; |
| 26 |
|
| 27 |
// Number of bytes representing the Huffman code. |
| 28 |
let byte = is.read::<8, u8>()?; |
| 29 |
let num_bytes = (byte + 1) as usize; |
| 30 |
|
| 31 |
let mut codeword_idx = 0; |
| 32 |
for _byte_idx in 0..num_bytes { |
| 33 |
let byte = is.read::<8, u16>()?; |
| 34 |
|
| 35 |
let codeword_len = (byte & 0xf) + 1; /* Low four bits plus one. */ |
| 36 |
let run_length = (byte >> 4) + 1; /* High four bits plus one. */ |
| 37 |
|
| 38 |
debug_assert!((1..=16).contains(&codeword_len)); |
| 39 |
len_count[codeword_len as usize - 1] += run_length; |
| 40 |
|
| 41 |
if (codeword_idx + run_length) as usize > num_lens { |
| 42 |
return Err(Error::new( |
| 43 |
io::ErrorKind::InvalidData, |
| 44 |
"too many codeword lengths", |
| 45 |
)); |
| 46 |
} |
| 47 |
for _ in 0..run_length { |
| 48 |
debug_assert!((codeword_idx as usize) < num_lens); |
| 49 |
lens[codeword_idx as usize] = codeword_len as u8; |
| 50 |
codeword_idx += 1; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
debug_assert!(codeword_idx as usize <= num_lens); |
| 55 |
if (codeword_idx as usize) < num_lens { |
| 56 |
return Err(Error::new( |
| 57 |
io::ErrorKind::InvalidData, |
| 58 |
"not enough codeword lengths", |
| 59 |
)); |
| 60 |
} |
| 61 |
|
| 62 |
// Check that the Huffman tree is full. |
| 63 |
let mut avail_codewords = 1; |
| 64 |
for i in 1..=16 { |
| 65 |
debug_assert!(avail_codewords >= 0); |
| 66 |
avail_codewords *= 2; |
| 67 |
avail_codewords -= i32::from(len_count[i - 1]); |
| 68 |
if avail_codewords < 0 { |
| 69 |
return Err(Error::new( |
| 70 |
io::ErrorKind::InvalidData, |
| 71 |
"huffman tree is not full", |
| 72 |
)); |
| 73 |
} |
| 74 |
} |
| 75 |
if avail_codewords != 0 { |
| 76 |
// Not all codewords were used. |
| 77 |
return Err(Error::new( |
| 78 |
io::ErrorKind::InvalidData, |
| 79 |
"not all codewords were used", |
| 80 |
)); |
| 81 |
} |
| 82 |
|
| 83 |
let mut d = Box::new(HuffmanDecoder::default()); |
| 84 |
d.init(&lens, num_lens)?; |
| 85 |
Ok(d) |
| 86 |
} |
| 87 |
|
| 88 |
fn hwexplode( |
| 89 |
src: &[u8], |
| 90 |
uncomp_len: usize, |
| 91 |
large_wnd: bool, |
| 92 |
lit_tree: bool, |
| 93 |
pk101_bug_compat: bool, |
| 94 |
dst: &mut Vec<u8>, |
| 95 |
) -> std::io::Result<()> { |
| 96 |
// Pre-allocate capacity |
| 97 |
dst.reserve(uncomp_len); |
| 98 |
|
| 99 |
let bit_length = src.len() as u64 * 8; |
| 100 |
let mut is = BitReader::endian(Cursor::new(&src), LittleEndian); |
| 101 |
let mut lit_decoder_opt = if lit_tree { |
| 102 |
Some(read_huffman_code(&mut is, 256)?) |
| 103 |
} else { |
| 104 |
None |
| 105 |
}; |
| 106 |
let mut len_decoder = read_huffman_code(&mut is, 64)?; |
| 107 |
let mut dist_decoder = read_huffman_code(&mut is, 64)?; |
| 108 |
let min_len = if (pk101_bug_compat && large_wnd) || (!pk101_bug_compat && lit_tree) { |
| 109 |
3 |
| 110 |
} else { |
| 111 |
2 |
| 112 |
}; |
| 113 |
let dist_low_bits = if large_wnd { 7 } else { 6 }; |
| 114 |
|
| 115 |
while dst.len() < uncomp_len { |
| 116 |
let is_literal = is.read_bit()?; |
| 117 |
if is_literal { |
| 118 |
// Literal. |
| 119 |
let sym; |
| 120 |
if let Some(lit_decoder) = &mut lit_decoder_opt { |
| 121 |
sym = lit_decoder.huffman_decode(bit_length, &mut is)?; |
| 122 |
} else { |
| 123 |
sym = u16::from(is.read::<8, u8>()?); |
| 124 |
} |
| 125 |
debug_assert!(sym <= u16::from(u8::MAX)); |
| 126 |
dst.push(sym as u8); |
| 127 |
continue; |
| 128 |
} |
| 129 |
|
| 130 |
// Read the low dist bits. |
| 131 |
let mut dist = is.read_var::<u16>(dist_low_bits)?; |
| 132 |
// Read the Huffman-encoded high dist bits. |
| 133 |
let sym = dist_decoder.huffman_decode(bit_length, &mut is)?; |
| 134 |
dist |= (sym as u16) << dist_low_bits; |
| 135 |
dist += 1; |
| 136 |
|
| 137 |
// Read the Huffman-encoded len. |
| 138 |
let sym = len_decoder.huffman_decode(bit_length, &mut is)?; |
| 139 |
let mut len = (sym + min_len) as usize; |
| 140 |
|
| 141 |
if sym == MAX_LEN_SYMBOL { |
| 142 |
// Read an extra len byte. |
| 143 |
len += is.read::<8, u16>()? as usize; |
| 144 |
} |
| 145 |
let len = len.min(uncomp_len - dst.len()); |
| 146 |
|
| 147 |
// Optimize the copy loop using extend_from_within when possible |
| 148 |
if dist as usize <= dst.len() { |
| 149 |
if dist as usize >= len { |
| 150 |
// No overlap in copy, can use extend_from_within |
| 151 |
let start = dst.len() - dist as usize; |
| 152 |
dst.extend_from_within(start..start + len); |
| 153 |
} else { |
| 154 |
// Overlapping copy |
| 155 |
for _ in 0..len { |
| 156 |
let byte = dst[dst.len() - dist as usize]; |
| 157 |
dst.push(byte); |
| 158 |
} |
| 159 |
} |
| 160 |
} else { |
| 161 |
// Copy with implicit zeros |
| 162 |
for _ in 0..len { |
| 163 |
if dist as usize > dst.len() { |
| 164 |
dst.push(0); |
| 165 |
} else { |
| 166 |
let byte = dst[dst.len() - dist as usize]; |
| 167 |
dst.push(byte); |
| 168 |
} |
| 169 |
} |
| 170 |
} |
| 171 |
} |
| 172 |
Ok(()) |
| 173 |
} |
| 174 |
|
| 175 |
#[derive(Debug)] |
| 176 |
pub struct ImplodeDecoder<R> { |
| 177 |
compressed_reader: R, |
| 178 |
uncompressed_size: u64, |
| 179 |
stream_read: bool, |
| 180 |
large_wnd: bool, |
| 181 |
lit_tree: bool, |
| 182 |
stream: Vec<u8>, |
| 183 |
read_pos: usize, // Add read position tracker |
| 184 |
} |
| 185 |
|
| 186 |
impl<R: Read> ImplodeDecoder<R> { |
| 187 |
pub fn new(inner: R, uncompressed_size: u64, flags: u16) -> Self { |
| 188 |
let large_wnd = (flags & 2) != 0; |
| 189 |
let lit_tree = (flags & 4) != 0; |
| 190 |
ImplodeDecoder { |
| 191 |
compressed_reader: inner, |
| 192 |
uncompressed_size, |
| 193 |
stream_read: false, |
| 194 |
large_wnd, |
| 195 |
lit_tree, |
| 196 |
stream: Vec::new(), |
| 197 |
read_pos: 0, |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
pub fn into_inner(self) -> R { |
| 202 |
self.compressed_reader |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
impl<R: Read> Read for ImplodeDecoder<R> { |
| 207 |
fn read(&mut self, buf: &mut [u8]) -> Result<usize> { |
| 208 |
if !self.stream_read { |
| 209 |
self.stream_read = true; |
| 210 |
let mut compressed_bytes = Vec::new(); |
| 211 |
self.compressed_reader.read_to_end(&mut compressed_bytes)?; |
| 212 |
|
| 213 |
// Pre-allocate stream buffer |
| 214 |
self.stream.reserve(self.uncompressed_size as usize); |
| 215 |
|
| 216 |
hwexplode( |
| 217 |
&compressed_bytes, |
| 218 |
self.uncompressed_size as usize, |
| 219 |
self.large_wnd, |
| 220 |
self.lit_tree, |
| 221 |
false, |
| 222 |
&mut self.stream, |
| 223 |
)?; |
| 224 |
} |
| 225 |
|
| 226 |
let available = self.stream.len() - self.read_pos; |
| 227 |
let bytes_to_read = available.min(buf.len()); |
| 228 |
buf[..bytes_to_read] |
| 229 |
.copy_from_slice(&self.stream[self.read_pos..self.read_pos + bytes_to_read]); |
| 230 |
self.read_pos += bytes_to_read; |
| 231 |
Ok(bytes_to_read) |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
#[cfg(test)] |
| 236 |
mod tests { |
| 237 |
use super::hwexplode; |
| 238 |
|
| 239 |
const HAMLET_256: &[u8; 249] = include_bytes!("../../tests/data/legacy/implode_hamlet_256.bin"); |
| 240 |
const HAMLET_256_OUT: &[u8; 256] = |
| 241 |
include_bytes!("../../tests/data/legacy/implode_hamlet_256.out"); |
| 242 |
|
| 243 |
#[test] |
| 244 |
fn test_explode_hamlet_256() { |
| 245 |
let mut dst = Vec::new(); |
| 246 |
hwexplode(HAMLET_256, 256, false, false, false, &mut dst).unwrap(); |
| 247 |
assert_eq!(dst.len(), 256); |
| 248 |
assert_eq!(&dst, &HAMLET_256_OUT); |
| 249 |
} |
| 250 |
} |