1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use crate::cbuffer::CircularBuffer;
use crate::error::CompressionError;
use crate::lzss::LzssCode;
use crate::traits::decoder::Decoder;
#[derive(Debug)]
pub struct LzssDecoder {
buf: CircularBuffer<u8>,
offset: usize,
}
impl LzssDecoder {
pub fn new(size_of_window: usize) -> Self {
Self {
buf: CircularBuffer::new(size_of_window),
offset: 0,
}
}
pub fn with_dict(size_of_window: usize, dict: &[u8]) -> Self {
let mut buf = CircularBuffer::new(size_of_window);
buf.append(dict);
Self { buf, offset: 0 }
}
}
impl Decoder for LzssDecoder {
type Input = LzssCode;
type Error = CompressionError;
type Output = u8;
fn next<I: Iterator<Item = Self::Input>>(
&mut self,
s: &mut I,
) -> Option<Result<Self::Output, Self::Error>> {
while self.offset == 0 {
match s.next() {
Some(s) => match s {
LzssCode::Symbol(s) => {
self.buf.push(s);
self.offset += 1;
}
LzssCode::Reference { len, pos } => {
self.offset += len;
for _ in 0..len {
let d = self.buf[pos];
self.buf.push(d);
}
}
},
None => return None,
}
}
self.offset -= 1;
Some(Ok(self.buf[self.offset]))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::action::Action;
use crate::lzss::encoder::LzssEncoder;
use crate::lzss::tests::comparison;
use crate::traits::encoder::Encoder;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[test]
fn test() {
let testvec = b"aabbaabbaaabbbaaabbbaabbaabb";
let mut encoder = LzssEncoder::new(comparison, 0x1_0000, 256, 3, 3);
let mut iter = testvec.iter().cloned();
let enc_ret = (0..)
.scan((), |_, _| encoder.next(&mut iter, Action::Flush))
.map(Result::unwrap)
.collect::<Vec<_>>();
let mut decoder = LzssDecoder::new(0x1_0000);
let mut dec_iter = enc_ret.into_iter();
let ret = (0..)
.scan((), |_, _| decoder.next(&mut dec_iter))
.map(Result::unwrap)
.collect::<Vec<_>>();
assert_eq!(testvec.to_vec(), ret);
}
}