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
//! rust-compression
//!
//! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! <http://mozilla.org/MPL/2.0/>.
//!

use crate::action::Action;
use crate::error::CompressionError;

pub trait EncodeExt<I>
where
    I: Iterator,
{
    fn encode<E: Encoder<In = I::Item>>(
        self,
        encoder: &mut E,
        action: Action,
    ) -> EncodeIterator<'_, I, E>
    where
        CompressionError: From<E::Error>;
}

impl<I> EncodeExt<I::IntoIter> for I
where
    I: IntoIterator,
{
    fn encode<E: Encoder<In = I::Item>>(
        self,
        encoder: &mut E,
        action: Action,
    ) -> EncodeIterator<'_, I::IntoIter, E>
    where
        CompressionError: From<E::Error>,
    {
        EncodeIterator::<I::IntoIter, E>::new(self.into_iter(), encoder, action)
    }
}

#[derive(Debug)]
pub struct EncodeIterator<'a, I, E>
where
    I: Iterator<Item = E::In>,
    E: Encoder,
    CompressionError: From<E::Error>,
{
    encoder: &'a mut E,
    action: Action,
    inner: I,
}

impl<'a, I, E> EncodeIterator<'a, I, E>
where
    I: Iterator<Item = E::In>,
    E: Encoder,
    CompressionError: From<E::Error>,
{
    fn new(inner: I, encoder: &'a mut E, action: Action) -> Self {
        Self {
            encoder,
            inner,
            action,
        }
    }
}

impl<I, E> Iterator for EncodeIterator<'_, I, E>
where
    I: Iterator<Item = E::In>,
    E: Encoder,
    CompressionError: From<E::Error>,
{
    type Item = Result<E::Out, E::Error>;

    fn next(&mut self) -> Option<Result<E::Out, E::Error>> {
        self.encoder.next(&mut self.inner, self.action)
    }
}

pub trait Encoder
where
    CompressionError: From<Self::Error>,
{
    type Error;
    type In;
    type Out;
    fn next<I: Iterator<Item = Self::In>>(
        &mut self,
        iter: &mut I,
        action: Action,
    ) -> Option<Result<Self::Out, Self::Error>>;
}