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
use bitio::direction::Direction;
use bitio::reader::BitReader;
use core::borrow::BorrowMut;
use core::marker::PhantomData;
use error::CompressionError;
pub trait DecodeExt<I, R>
where
I: Iterator<Item = u8>,
{
fn decode<E: Decoder<R>>(self, decoder: &mut E) -> DecodeIterator<R, E, R>
where
CompressionError: From<E::Error>;
}
impl<I, D> DecodeExt<I::IntoIter, BitReader<D, I::IntoIter>> for I
where
D: Direction,
I: IntoIterator<Item = u8>,
{
fn decode<E: Decoder<BitReader<D, I::IntoIter>>>(
self,
decoder: &mut E,
) -> DecodeIterator<BitReader<D, I::IntoIter>, E, BitReader<D, I::IntoIter>>
where
D: Direction,
E: Decoder<BitReader<D, I::IntoIter>>,
CompressionError: From<E::Error>,
{
DecodeIterator::<
BitReader<D, I::IntoIter>,
E,
BitReader<D, I::IntoIter>,
>::new(BitReader::<D, _>::new(self.into_iter()), decoder)
}
}
pub struct DecodeIterator<'a, R, E, B>
where
E: Decoder<R> + 'a,
B: BorrowMut<R>,
CompressionError: From<E::Error>,
{
decoder: &'a mut E,
inner: B,
phantom: PhantomData<fn() -> R>,
}
impl<'a, R, E, B> DecodeIterator<'a, R, E, B>
where
E: Decoder<R>,
B: BorrowMut<R>,
CompressionError: From<E::Error>,
{
fn new(inner: B, decoder: &'a mut E) -> Self {
Self {
decoder,
inner,
phantom: PhantomData,
}
}
}
impl<'a, R, E, B> Iterator for DecodeIterator<'a, R, E, B>
where
E: Decoder<R>,
B: BorrowMut<R>,
CompressionError: From<E::Error>,
{
type Item = Result<E::Output, E::Error>;
fn next(&mut self) -> Option<Result<E::Output, E::Error>> {
match self.decoder.next(&mut self.inner.borrow_mut()) {
Ok(Some(s)) => Some(Ok(s)),
Ok(None) => None,
Err(s) => Some(Err(s)),
}
}
}
pub trait Decoder<R>
where
CompressionError: From<Self::Error>,
{
type Error;
type Output;
fn next(
&mut self,
iter: &mut R,
) -> Result<Option<Self::Output>, Self::Error>;
fn iter<'a>(
&'a mut self,
reader: &'a mut R,
) -> DecodeIterator<R, Self, &'a mut R>
where
Self: Sized,
{
DecodeIterator {
decoder: self,
inner: reader,
phantom: PhantomData,
}
}
}