| 1 |
use std::io::{self, Read, Result}; |
| 2 |
|
| 3 |
use bitstream_io::{BitRead, BitReader, Endianness, LittleEndian}; |
| 4 |
|
| 5 |
/// Number of bits used to represent indices in a follower set of size n. |
| 6 |
const fn follower_idx_bitlen(n: u8) -> u8 { |
| 7 |
debug_assert!(n <= 32); |
| 8 |
match n { |
| 9 |
0 => 0, |
| 10 |
1 => 1, |
| 11 |
_ => 8 - (n - 1).leading_zeros() as u8, |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
#[derive(Default, Clone, Copy)] |
| 16 |
struct FollowerSet { |
| 17 |
followers: [u8; 32], |
| 18 |
size: u8, |
| 19 |
idx_bitlen: u8, |
| 20 |
} |
| 21 |
|
| 22 |
/// Read the follower sets from is into fsets. Returns true on success. |
| 23 |
type FollowerSetArray = [FollowerSet; u8::MAX as usize + 1]; |
| 24 |
|
| 25 |
fn read_follower_sets<T: Read, E: Endianness>( |
| 26 |
is: &mut BitReader<T, E>, |
| 27 |
) -> io::Result<FollowerSetArray> { |
| 28 |
let mut fsets = [FollowerSet::default(); u8::MAX as usize + 1]; |
| 29 |
for i in (0..=u8::MAX as usize).rev() { |
| 30 |
let n = is.read::<6, u8>()?; |
| 31 |
if n > 32 { |
| 32 |
return Err(io::Error::new( |
| 33 |
io::ErrorKind::InvalidData, |
| 34 |
"invalid follower set", |
| 35 |
)); |
| 36 |
} |
| 37 |
fsets[i].size = n; |
| 38 |
fsets[i].idx_bitlen = follower_idx_bitlen(n); |
| 39 |
|
| 40 |
for j in 0..fsets[i].size as usize { |
| 41 |
fsets[i].followers[j] = is.read::<8, u8>()?; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
Ok(fsets) |
| 46 |
} |
| 47 |
|
| 48 |
/// Read the next byte from is, decoded based on prev_byte and the follower sets. |
| 49 |
/// The byte is returned in *out_byte. |
| 50 |
/// |
| 51 |
/// # Returns |
| 52 |
/// |
| 53 |
/// * `Ok` with the byte if it was successfully read. |
| 54 |
/// * `Err(io::Error)` on bad data or end of input. |
| 55 |
fn read_next_byte<T: Read, E: Endianness>( |
| 56 |
is: &mut BitReader<T, E>, |
| 57 |
prev_byte: u8, |
| 58 |
fsets: &mut FollowerSetArray, |
| 59 |
) -> io::Result<u8> { |
| 60 |
if fsets[prev_byte as usize].size == 0 // No followers |
| 61 |
|| is.read::<1, u8>()? == 1 |
| 62 |
// Indicates next symbol is a literal byte |
| 63 |
{ |
| 64 |
return is.read::<8, u8>(); |
| 65 |
} |
| 66 |
|
| 67 |
// The bits represent the index of a follower byte. |
| 68 |
let idx_bitlen = fsets[prev_byte as usize].idx_bitlen; |
| 69 |
let follower_idx = is.read_var::<u16>(u32::from(idx_bitlen))? as usize; |
| 70 |
if follower_idx >= fsets[prev_byte as usize].size as usize { |
| 71 |
return Err(io::Error::new( |
| 72 |
io::ErrorKind::InvalidData, |
| 73 |
"invalid follower index", |
| 74 |
)); |
| 75 |
} |
| 76 |
Ok(fsets[prev_byte as usize].followers[follower_idx]) |
| 77 |
} |
| 78 |
|
| 79 |
fn max_len(comp_factor: u8) -> usize { |
| 80 |
debug_assert!((1..=4).contains(&comp_factor)); |
| 81 |
let v_len_bits = (8 - comp_factor) as usize; |
| 82 |
// Bits in V + extra len byte + implicit 3. |
| 83 |
((1 << v_len_bits) - 1) + u8::MAX as usize + 3 |
| 84 |
} |
| 85 |
|
| 86 |
fn max_dist(comp_factor: u8) -> usize { |
| 87 |
debug_assert!((1..=4).contains(&comp_factor)); |
| 88 |
let v_dist_bits = comp_factor as usize; |
| 89 |
// Bits in V * 256 + W byte + implicit 1. */ |
| 90 |
1 << (v_dist_bits + 8) |
| 91 |
} |
| 92 |
|
| 93 |
const DLE_BYTE: u8 = 0x90; |
| 94 |
|
| 95 |
/// Get the n least significant bits of x. |
| 96 |
fn lsb(x: u8, n: u8) -> u8 { |
| 97 |
if n >= 8 { |
| 98 |
return x; |
| 99 |
} |
| 100 |
x & ((1 << n) - 1) |
| 101 |
} |
| 102 |
|
| 103 |
fn hwexpand(src: &[u8], uncomp_len: usize, comp_factor: u8, dst: &mut Vec<u8>) -> io::Result<()> { |
| 104 |
debug_assert!((1..=4).contains(&comp_factor)); |
| 105 |
|
| 106 |
// Pre-allocate to avoid reallocations |
| 107 |
dst.reserve(uncomp_len); |
| 108 |
|
| 109 |
let mut is = BitReader::endian(src, LittleEndian); |
| 110 |
let mut fsets = read_follower_sets(&mut is)?; |
| 111 |
|
| 112 |
// Number of bits in V used for backref length. |
| 113 |
let v_len_bits = 8 - comp_factor; |
| 114 |
|
| 115 |
let mut curr_byte = 0; // The first "previous byte" is implicitly zero. |
| 116 |
|
| 117 |
while dst.len() < uncomp_len { |
| 118 |
// Read a literal byte or DLE marker. |
| 119 |
curr_byte = read_next_byte(&mut is, curr_byte, &mut fsets)?; |
| 120 |
if curr_byte != DLE_BYTE { |
| 121 |
// Output a literal byte. |
| 122 |
dst.push(curr_byte); |
| 123 |
continue; |
| 124 |
} |
| 125 |
|
| 126 |
// Read the V byte which determines the length. |
| 127 |
curr_byte = read_next_byte(&mut is, curr_byte, &mut fsets)?; |
| 128 |
if curr_byte == 0 { |
| 129 |
// Output a literal DLE byte. |
| 130 |
dst.push(DLE_BYTE); |
| 131 |
continue; |
| 132 |
} |
| 133 |
let v = curr_byte; |
| 134 |
let mut len = lsb(v, v_len_bits) as usize; |
| 135 |
if len == (1 << v_len_bits) - 1 { |
| 136 |
// Read an extra length byte. |
| 137 |
curr_byte = read_next_byte(&mut is, curr_byte, &mut fsets)?; |
| 138 |
len += curr_byte as usize; |
| 139 |
} |
| 140 |
len += 3; |
| 141 |
|
| 142 |
// Read the W byte, which together with V gives the distance. |
| 143 |
curr_byte = read_next_byte(&mut is, curr_byte, &mut fsets)?; |
| 144 |
let dist = (((v as usize) >> v_len_bits) << 8) + curr_byte as usize + 1; |
| 145 |
|
| 146 |
debug_assert!(len <= max_len(comp_factor)); |
| 147 |
debug_assert!(dist <= max_dist(comp_factor)); |
| 148 |
|
| 149 |
// Output the back reference. |
| 150 |
if dist <= dst.len() { |
| 151 |
// Optimize for non-overlapping copies |
| 152 |
if dist >= len { |
| 153 |
// No overlap, can use extend_from_within |
| 154 |
let start = dst.len() - dist; |
| 155 |
dst.extend_from_within(start..start + len.min(uncomp_len - dst.len())); |
| 156 |
} else { |
| 157 |
// Overlapping copy |
| 158 |
let copy_len = len.min(uncomp_len - dst.len()); |
| 159 |
for _ in 0..copy_len { |
| 160 |
let byte = dst[dst.len() - dist]; |
| 161 |
dst.push(byte); |
| 162 |
} |
| 163 |
} |
| 164 |
} else { |
| 165 |
// Copy with implicit zeros |
| 166 |
let copy_len = len.min(uncomp_len - dst.len()); |
| 167 |
for _ in 0..copy_len { |
| 168 |
if dist > dst.len() { |
| 169 |
dst.push(0); |
| 170 |
} else { |
| 171 |
let byte = dst[dst.len() - dist]; |
| 172 |
dst.push(byte); |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
} |
| 177 |
Ok(()) |
| 178 |
} |
| 179 |
|
| 180 |
#[derive(Debug)] |
| 181 |
pub struct ReduceDecoder<R> { |
| 182 |
compressed_reader: R, |
| 183 |
uncompressed_size: u64, |
| 184 |
stream_read: bool, |
| 185 |
comp_factor: u8, |
| 186 |
stream: Vec<u8>, |
| 187 |
read_pos: usize, // Add read position tracker |
| 188 |
} |
| 189 |
|
| 190 |
impl<R: Read> ReduceDecoder<R> { |
| 191 |
pub fn new(inner: R, uncompressed_size: u64, comp_factor: u8) -> Self { |
| 192 |
ReduceDecoder { |
| 193 |
compressed_reader: inner, |
| 194 |
uncompressed_size, |
| 195 |
stream_read: false, |
| 196 |
comp_factor, |
| 197 |
stream: Vec::new(), |
| 198 |
read_pos: 0, |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
pub fn into_inner(self) -> R { |
| 203 |
self.compressed_reader |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
impl<R: Read> Read for ReduceDecoder<R> { |
| 208 |
fn read(&mut self, buf: &mut [u8]) -> Result<usize> { |
| 209 |
if !self.stream_read { |
| 210 |
self.stream_read = true; |
| 211 |
let mut compressed_bytes = Vec::new(); |
| 212 |
self.compressed_reader.read_to_end(&mut compressed_bytes)?; |
| 213 |
hwexpand( |
| 214 |
&compressed_bytes, |
| 215 |
self.uncompressed_size as usize, |
| 216 |
self.comp_factor, |
| 217 |
&mut self.stream, |
| 218 |
)?; |
| 219 |
} |
| 220 |
|
| 221 |
let available = self.stream.len() - self.read_pos; |
| 222 |
let bytes_to_read = available.min(buf.len()); |
| 223 |
buf[..bytes_to_read] |
| 224 |
.copy_from_slice(&self.stream[self.read_pos..self.read_pos + bytes_to_read]); |
| 225 |
self.read_pos += bytes_to_read; |
| 226 |
Ok(bytes_to_read) |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
#[cfg(test)] |
| 231 |
mod tests { |
| 232 |
use super::hwexpand; |
| 233 |
use crate::legacy::reduce::{follower_idx_bitlen, lsb, max_dist}; |
| 234 |
const HAMLET_2048: &[u8; 1285] = |
| 235 |
include_bytes!("../../tests/data/legacy/reduce_hamlet_2048.bin"); |
| 236 |
const HAMLET_2048_OUT: &[u8; 2048] = |
| 237 |
include_bytes!("../../tests/data/legacy/implode_hamlet_2048.out"); |
| 238 |
|
| 239 |
#[test] |
| 240 |
fn test_lsb() { |
| 241 |
assert_eq!(lsb(0xFF, 8), 0xFF); |
| 242 |
for i in 0..7 { |
| 243 |
assert_eq!(lsb(0xFF, i), (1 << i) - 1); |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
#[test] |
| 248 |
fn test_expand_hamlet2048() { |
| 249 |
let mut dst = Vec::new(); |
| 250 |
hwexpand(HAMLET_2048, 2048, 4, &mut dst).unwrap(); |
| 251 |
assert_eq!(dst.len(), 2048); |
| 252 |
assert_eq!(&dst, &HAMLET_2048_OUT); |
| 253 |
} |
| 254 |
|
| 255 |
/* |
| 256 |
Put some text first to make PKZIP actually use Reduce compression. |
| 257 |
Target the code path which copies a zero when dist > current position. |
| 258 |
|
| 259 |
$ curl -O http://cd.textfiles.com/originalsw/25/pkz092.exe |
| 260 |
$ dosbox -c "mount c ." -c "c:" -c "pkz092" -c "exit" |
| 261 |
$ dd if=hamlet.txt bs=1 count=2048 > a |
| 262 |
$ dd if=/dev/zero bs=1 count=1024 >> a |
| 263 |
$ dosbox -c "mount c ." -c "c:" -c "pkzip -ea4 a.zip a" -c "exit" |
| 264 |
$ xxd -i -s 31 -l $(expr $(find A.ZIP -printf %s) - 100) A.ZIP |
| 265 |
*/ |
| 266 |
const ZEROS_REDUCED: &[u8; 1297] = |
| 267 |
include_bytes!("../../tests/data/legacy/reduce_zero_reduced.bin"); |
| 268 |
|
| 269 |
#[test] |
| 270 |
fn test_expand_zeros() { |
| 271 |
let mut dst = Vec::new(); |
| 272 |
hwexpand(ZEROS_REDUCED, 2048 + 1024, 4, &mut dst).unwrap(); |
| 273 |
assert_eq!(dst.len(), 2048 + 1024); |
| 274 |
for i in 0..(1 << 10) { |
| 275 |
assert_eq!(dst[(1 << 11) + i], 0); |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
fn orig_follower_idx_bitlen(n: u8) -> u8 { |
| 280 |
if n > 16 { |
| 281 |
return 5; |
| 282 |
} |
| 283 |
if n > 8 { |
| 284 |
return 4; |
| 285 |
} |
| 286 |
if n > 4 { |
| 287 |
return 3; |
| 288 |
} |
| 289 |
if n > 2 { |
| 290 |
return 2; |
| 291 |
} |
| 292 |
if n > 0 { |
| 293 |
return 1; |
| 294 |
} |
| 295 |
0 |
| 296 |
} |
| 297 |
|
| 298 |
#[test] |
| 299 |
fn test_follower_idx_biten() { |
| 300 |
for i in 0..=32 { |
| 301 |
assert_eq!(orig_follower_idx_bitlen(i), follower_idx_bitlen(i)); |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
#[test] |
| 306 |
fn test_max_dist() { |
| 307 |
for i in 1..=4 { |
| 308 |
let v_dist_bits = i as usize; |
| 309 |
let c = 1 << (v_dist_bits + 8); |
| 310 |
assert_eq!(max_dist(i), c); |
| 311 |
} |
| 312 |
} |
| 313 |
} |