| 1 |
use core::num::NonZeroU16; |
| 2 |
#[cfg(not(feature = "std"))] |
| 3 |
use alloc::boxed::Box; |
| 4 |
use crate::error::LhaResult; |
| 5 |
use crate::stub_io::Read; |
| 6 |
use crate::decode::Decoder; |
| 7 |
use crate::ringbuf::*; |
| 8 |
use crate::bitstream::*; |
| 9 |
|
| 10 |
const RING_BUFFER_SIZE: usize = 2048; |
| 11 |
const START_OFFSET: isize = -17; |
| 12 |
|
| 13 |
/// A decoder for `-lzs-` compression method. |
| 14 |
#[derive(Debug)] |
| 15 |
pub struct LzsDecoder<R> { |
| 16 |
bit_reader: BitStream<R>, |
| 17 |
copy_progress: Option<(u16, NonZeroU16)>, |
| 18 |
ringbuf: Box<RingArrayBuf<RING_BUFFER_SIZE>>, |
| 19 |
} |
| 20 |
|
| 21 |
impl<R: Read> LzsDecoder<R> { |
| 22 |
pub fn new(rd: R) -> LzsDecoder<R> { |
| 23 |
let bit_reader = BitStream::new(rd); |
| 24 |
let mut ringbuf: Box<RingArrayBuf<RING_BUFFER_SIZE>> = Box::default(); |
| 25 |
ringbuf.set_cursor(START_OFFSET); |
| 26 |
LzsDecoder { |
| 27 |
bit_reader, |
| 28 |
ringbuf, |
| 29 |
copy_progress: None |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
fn copy_from_history<'a, I: Iterator<Item=&'a mut u8> + ExactSizeIterator>( |
| 34 |
&mut self, |
| 35 |
target: I, |
| 36 |
pos: usize, |
| 37 |
count: usize |
| 38 |
) -> LhaResult<(), R> |
| 39 |
{ |
| 40 |
let history_iter = self.ringbuf.iter_from_pos(pos); |
| 41 |
let real_count = target.len().min(count); |
| 42 |
for (t, s) in target.zip(history_iter).take(real_count) { |
| 43 |
*t = s; |
| 44 |
} |
| 45 |
self.copy_progress = NonZeroU16::new((count - real_count) as u16) |
| 46 |
.map(|count| ((pos + real_count) as u16, count)); |
| 47 |
Ok(()) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
impl<R: Read> Decoder<R> for LzsDecoder<R> where R::Error: core::fmt::Debug { |
| 52 |
type Error = R::Error; |
| 53 |
|
| 54 |
fn into_inner(self) -> R { |
| 55 |
self.bit_reader.into_inner() |
| 56 |
} |
| 57 |
|
| 58 |
fn fill_buffer(&mut self, buf: &mut[u8]) -> LhaResult<(), R> { |
| 59 |
let buflen = buf.len(); |
| 60 |
let mut target = buf.iter_mut(); |
| 61 |
if let Some((pos, count)) = self.copy_progress { |
| 62 |
self.copy_from_history(&mut target, |
| 63 |
pos as usize, |
| 64 |
count.get() as usize)?; |
| 65 |
} |
| 66 |
|
| 67 |
while let Some(dst) = target.next() { |
| 68 |
if self.bit_reader.read_bit()? { |
| 69 |
let value = self.bit_reader.read_bits(8)?; |
| 70 |
*dst = value; |
| 71 |
self.ringbuf.push(value); |
| 72 |
} |
| 73 |
else { |
| 74 |
let pos = self.bit_reader.read_bits(11)?; |
| 75 |
let count: usize = self.bit_reader.read_bits(4)?; |
| 76 |
let index = buflen - target.len() - 1; |
| 77 |
target = buf[index..].iter_mut(); |
| 78 |
self.copy_from_history(&mut target, pos, count + 2)?; |
| 79 |
} |
| 80 |
} |
| 81 |
Ok(()) |
| 82 |
} |
| 83 |
} |