Debian Codegraph @

debian/rust-vendor/zip/src/legacy/shrink.rs

raw
1 use std::io::{self, Error, Read};
2
3 use bitstream_io::{BitRead, BitReader, Endianness, LittleEndian};
4
5 const MIN_CODE_SIZE: u8 = 9;
6 const MAX_CODE_SIZE: u8 = 13;
7
8 const MAX_CODE: usize = (1 << MAX_CODE_SIZE) - 1;
9 const CONTROL_CODE: usize = 256;
10 const INC_CODE_SIZE: u16 = 1;
11 const PARTIAL_CLEAR: u16 = 2;
12
13 /// Number of codes available for the LZW dictionary (excluding control codes)
14 /// These are the codes from CONTROL_CODE+1 to MAX_CODE
15 const FREE_CODE_QUEUE_SIZE: usize = MAX_CODE - CONTROL_CODE + 1;
16
17 // const HASH_BITS: usize = MAX_CODE_SIZE + 1; /* For a load factor of 0.5. */
18 // const HASHTAB_SIZE: usize = 1 << HASH_BITS;
19 const UNKNOWN_LEN: u16 = u16::MAX;
20
21 struct CodeQueue {
22 next_idx: usize,
23 codes: [Option<u16>; FREE_CODE_QUEUE_SIZE],
24 }
25
26 impl CodeQueue {
27 fn new() -> Self {
28 let mut codes = [None; FREE_CODE_QUEUE_SIZE];
29 for (i, code) in ((CONTROL_CODE as u16 + 1)..=(MAX_CODE as u16 - 1)).enumerate() {
30 codes[i] = Some(code);
31 }
32 Self { next_idx: 0, codes }
33 }
34
35 // Return the next code in the queue, or INVALID_CODE if the queue is empty.
36 fn next(&self) -> Option<u16> {
37 // assert(q->next_idx < sizeof(q->codes) / sizeof(q->codes[0]));
38 if let Some(Some(next)) = self.codes.get(self.next_idx) {
39 Some(*next)
40 } else {
41 None
42 }
43 }
44
45 /// Return and remove the next code from the queue, or return INVALID_CODE if
46 /// the queue is empty.
47 fn remove_next(&mut self) -> Option<u16> {
48 let res = self.next();
49 if res.is_some() {
50 self.next_idx += 1;
51 }
52 res
53 }
54 }
55
56 #[derive(Clone, Debug, Copy, Default)]
57 struct Codetab {
58 last_dst_pos: usize,
59 prefix_code: Option<u16>,
60 len: u16,
61 ext_byte: u8,
62 }
63
64 impl Codetab {
65 pub fn create_new() -> [Self; MAX_CODE + 1] {
66 let mut codetab = [Codetab::default(); MAX_CODE + 1];
67 for (i, code) in codetab.iter_mut().enumerate().take(u8::MAX as usize + 1) {
68 *code = Codetab {
69 prefix_code: Some(i as u16),
70 ext_byte: i as u8,
71 len: 1,
72 last_dst_pos: 0,
73 };
74 }
75 codetab
76 }
77 }
78
79 fn unshrink_partial_clear(codetab: &mut [Codetab], queue: &mut CodeQueue) {
80 let mut is_prefix = [false; MAX_CODE + 1];
81
82 // Scan for codes that have been used as a prefix.
83 for code in codetab.iter().take(MAX_CODE + 1).skip(CONTROL_CODE + 1) {
84 if let Some(prefix_code) = code.prefix_code {
85 is_prefix[prefix_code as usize] = true;
86 }
87 }
88
89 // Clear "non-prefix" codes in the table; populate the code queue.
90 let mut code_queue_size = 0;
91 for i in (CONTROL_CODE + 1)..MAX_CODE {
92 if !is_prefix[i] {
93 codetab[i].prefix_code = None;
94 queue.codes[code_queue_size] = Some(i as u16);
95 code_queue_size += 1;
96 }
97 }
98 queue.codes[code_queue_size] = None; // End-of-queue marker.
99 queue.next_idx = 0;
100 }
101
102 /// Read the next code from the input stream and return it in next_code. Returns
103 /// `Ok(None)` if the end of the stream is reached. If the stream contains invalid
104 /// data, returns `Err`.
105 fn read_code<T: Read, E: Endianness>(
106 is: &mut BitReader<T, E>,
107 code_size: &mut u8,
108 codetab: &mut [Codetab],
109 queue: &mut CodeQueue,
110 ) -> io::Result<Option<u16>> {
111 // assert(sizeof(code) * CHAR_BIT >= *code_size);
112 let code = is.read_var::<u16>(u32::from(*code_size))?;
113
114 // Handle regular codes (the common case).
115 if code != CONTROL_CODE as u16 {
116 return Ok(Some(code));
117 }
118
119 // Handle control codes.
120 if let Ok(control_code) = is.read_var::<u16>(u32::from(*code_size)) {
121 match control_code {
122 INC_CODE_SIZE => {
123 if *code_size >= MAX_CODE_SIZE {
124 return Err(io::Error::new(
125 io::ErrorKind::InvalidData,
126 "tried to increase code size when already at maximum",
127 ));
128 }
129 *code_size += 1;
130 }
131 PARTIAL_CLEAR => {
132 unshrink_partial_clear(codetab, queue);
133 }
134 _ => {
135 return Err(io::Error::new(
136 io::ErrorKind::InvalidData,
137 format!("Invalid control code {}", control_code),
138 ));
139 }
140 }
141 return read_code(is, code_size, codetab, queue);
142 }
143 Ok(None)
144 }
145
146 /// Output the string represented by a code into dst at dst_pos.
147 ///
148 /// # Returns
149 /// new first byte of the string, or io::Error InvalidData on invalid prefix code.
150 fn output_code(
151 dst: &mut Vec<u8>,
152 code: u16,
153 prev_code: u16,
154 codetab: &mut [Codetab],
155 queue: &CodeQueue,
156 first_byte: u8,
157 ) -> io::Result<u8> {
158 debug_assert!(code <= MAX_CODE as u16 && code != CONTROL_CODE as u16);
159 if code <= u16::from(u8::MAX) {
160 dst.push(code as u8);
161 return Ok(code as u8);
162 }
163 if codetab[code as usize].prefix_code.is_none()
164 || codetab[code as usize].prefix_code == Some(code)
165 {
166 // Reject invalid codes. Self-referential codes may exist in
167 // the table but cannot be used.
168 return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid code"));
169 }
170 if codetab[code as usize].len != UNKNOWN_LEN {
171 // Output string with known length (the common case).
172 let ct = &codetab[code as usize];
173 for i in ct.last_dst_pos..ct.last_dst_pos + ct.len as usize {
174 dst.push(dst[i]);
175 }
176 return Ok(dst[ct.last_dst_pos]);
177 }
178
179 // Output a string of unknown length. This happens when the prefix
180 // was invalid (due to partial clearing) when the code was inserted into
181 // the table. The prefix can then become valid when it's added to the
182 // table at a later point.
183 let prefix_code = codetab[code as usize]
184 .prefix_code
185 .ok_or_else(|| io::Error::other("Cannot get prefix code"))?;
186 if cfg!(debug_assertions) {
187 let tab_entry = codetab[code as usize];
188 assert!(tab_entry.len == UNKNOWN_LEN);
189 assert!(
190 tab_entry
191 .prefix_code
192 .ok_or_else(|| io::Error::other("Cannot get prefix code"))? as usize
193 > CONTROL_CODE
194 );
195 }
196
197 if Some(prefix_code) == queue.next() {
198 /* The prefix code hasn't been added yet, but we were just
199 about to: the KwKwK case. Add the previous string extended
200 with its first byte. */
201 codetab[prefix_code as usize] = Codetab {
202 prefix_code: Some(prev_code),
203 ext_byte: first_byte,
204 len: codetab[prev_code as usize].len + 1,
205 last_dst_pos: codetab[prev_code as usize].last_dst_pos,
206 };
207 dst.push(first_byte);
208 } else if codetab[prefix_code as usize].prefix_code.is_none() {
209 // The prefix code is still invalid.
210 return Err(io::Error::new(
211 io::ErrorKind::InvalidData,
212 "invalid prefix code",
213 ));
214 }
215
216 // Output the prefix string, then the extension byte.
217 let ct = codetab[prefix_code as usize];
218 let last_dst_pos = dst.len();
219 let start = ct.last_dst_pos;
220 let len = ct.len as usize;
221 let first = dst[start];
222 dst.extend_from_within(start..start + len);
223 dst.push(codetab[code as usize].ext_byte);
224 // Update the code table now that the string has a length and pos.
225 debug_assert!(prev_code != code);
226
227 codetab[code as usize].len = (len + 1) as u16;
228 codetab[code as usize].last_dst_pos = last_dst_pos;
229
230 Ok(first)
231 }
232
233 fn hwunshrink(src: &[u8], uncompressed_size: usize, dst: &mut Vec<u8>) -> io::Result<()> {
234 dst.reserve(uncompressed_size);
235 let mut codetab = Codetab::create_new();
236 let mut queue = CodeQueue::new();
237 let mut is = BitReader::endian(src, LittleEndian);
238 let mut code_size = MIN_CODE_SIZE;
239
240 // Handle the first code separately since there is no previous code.
241 let Some(curr_code) = read_code(&mut is, &mut code_size, &mut codetab, &mut queue)? else {
242 return Ok(());
243 };
244
245 debug_assert!(curr_code != CONTROL_CODE as u16);
246 if curr_code > u16::from(u8::MAX) {
247 return Err(io::Error::new(
248 io::ErrorKind::InvalidData,
249 "the first code must be a literal",
250 ));
251 }
252 let mut first_byte = curr_code as u8; // make mutable
253 codetab[curr_code as usize].last_dst_pos = dst.len();
254 dst.push(first_byte);
255 let mut prev_code = curr_code;
256 while dst.len() < uncompressed_size {
257 let curr_opt = match read_code(&mut is, &mut code_size, &mut codetab, &mut queue) {
258 Ok(c) => c,
259 Err(_) => break, // treat read error as end-of-stream for now; validated after loop
260 };
261
262 let Some(curr_code) = curr_opt else {
263 return Err(Error::new(io::ErrorKind::InvalidData, "invalid code"));
264 };
265
266 let dst_pos = dst.len();
267 // Handle KwKwK: next code used before being added.
268 if Some(curr_code) == queue.next() {
269 if codetab[prev_code as usize].prefix_code.is_none() {
270 return Err(Error::new(
271 io::ErrorKind::InvalidData,
272 "previous code no longer valid",
273 ));
274 }
275 // Extend the previous code with its first byte.
276 debug_assert!(curr_code != prev_code);
277 codetab[curr_code as usize] = Codetab {
278 prefix_code: Some(prev_code),
279 ext_byte: first_byte,
280 len: codetab[prev_code as usize].len + 1,
281 last_dst_pos: codetab[prev_code as usize].last_dst_pos,
282 };
283 }
284 // Output the string represented by the current code.
285 first_byte = output_code(dst, curr_code, prev_code, &mut codetab, &queue, first_byte)?;
286 if let Some(new_code) = queue.remove_next() {
287 let prev_entry = codetab[prev_code as usize];
288 codetab[new_code as usize] = Codetab {
289 prefix_code: Some(prev_code),
290 ext_byte: first_byte,
291 last_dst_pos: prev_entry.last_dst_pos,
292 len: if prev_entry.prefix_code.is_none() {
293 // prev_code was invalidated in a partial
294 // clearing. Until that code is re-used, the
295 // string represented by new_code is
296 // indeterminate.
297 UNKNOWN_LEN
298 } else {
299 prev_entry.len + 1
300 },
301 };
302 }
303 codetab[curr_code as usize].last_dst_pos = dst_pos;
304 prev_code = curr_code;
305 }
306
307 if dst.len() != uncompressed_size {
308 return Err(io::Error::new(
309 io::ErrorKind::UnexpectedEof,
310 "unexpected end of compressed stream",
311 ));
312 }
313
314 Ok(())
315 }
316
317 #[derive(Debug)]
318 pub struct ShrinkDecoder<R> {
319 compressed_reader: R,
320 stream_read: bool,
321 uncompressed_size: u64,
322 stream: Vec<u8>,
323 read_pos: usize,
324 }
325
326 impl<R: Read> ShrinkDecoder<R> {
327 pub fn new(inner: R, uncompressed_size: u64) -> Self {
328 Self {
329 compressed_reader: inner,
330 uncompressed_size,
331 stream_read: false,
332 stream: Vec::new(),
333 read_pos: 0,
334 }
335 }
336 pub fn into_inner(self) -> R {
337 self.compressed_reader
338 }
339 }
340
341 impl<R: Read> Read for ShrinkDecoder<R> {
342 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
343 if !self.stream_read {
344 self.stream_read = true;
345 let mut compressed_bytes = Vec::new();
346 self.compressed_reader.read_to_end(&mut compressed_bytes)?;
347 self.stream.reserve(self.uncompressed_size as usize);
348 hwunshrink(
349 &compressed_bytes,
350 self.uncompressed_size as usize,
351 &mut self.stream,
352 )?;
353 }
354 let available = self.stream.len().saturating_sub(self.read_pos);
355 if available == 0 {
356 return Ok(0);
357 }
358 let n = available.min(buf.len());
359 buf[..n].copy_from_slice(&self.stream[self.read_pos..self.read_pos + n]);
360 self.read_pos += n;
361 Ok(n)
362 }
363 }
364
365 #[cfg(test)]
366 mod tests {
367 use crate::legacy::shrink::hwunshrink;
368
369 const LZW_FIG5: &[u8; 17] = b"ababcbababaaaaaaa";
370 const LZW_FIG5_SHRUNK: [u8; 12] = [
371 0x61, 0xc4, 0x04, 0x1c, 0x23, 0xb0, 0x60, 0x98, 0x83, 0x08, 0xc3, 0x00,
372 ];
373
374 #[test]
375 fn test_unshrink_lzw_fig5() {
376 let mut dst = Vec::with_capacity(LZW_FIG5.len());
377 hwunshrink(&LZW_FIG5_SHRUNK, LZW_FIG5.len(), &mut dst).unwrap();
378 assert_eq!(dst.as_slice(), LZW_FIG5);
379 }
380 }