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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use crate::encoding::hybrid_rle::{self, BitmapIter};

/// The decoding state of the hybrid-RLE decoder with a maximum definition level of 1
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HybridEncoded<'a> {
    /// a bitmap
    Bitmap(&'a [u8], usize),
    /// A repeated item. The first attribute corresponds to whether the value is set
    /// the second attribute corresponds to the number of repetitions.
    Repeated(bool, usize),
}

impl<'a> HybridEncoded<'a> {
    /// Returns the length of the run in number of items
    #[inline]
    pub fn len(&self) -> usize {
        match self {
            HybridEncoded::Bitmap(_, length) => *length,
            HybridEncoded::Repeated(_, length) => *length,
        }
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

pub trait HybridRleRunsIterator<'a>: Iterator<Item = HybridEncoded<'a>> {
    /// Number of elements remaining. This may not be the items of the iterator - an item
    /// of the iterator may contain more than one element.
    fn number_of_elements(&self) -> usize;
}

/// An iterator of [`HybridEncoded`], adapter over [`hybrid_rle::HybridEncoded`].
#[derive(Debug, Clone)]
pub struct HybridRleIter<'a, I: Iterator<Item = hybrid_rle::HybridEncoded<'a>>> {
    iter: I,
    length: usize,
    consumed: usize,
}

impl<'a, I: Iterator<Item = hybrid_rle::HybridEncoded<'a>>> HybridRleIter<'a, I> {
    /// Returns a new [`HybridRleIter`]
    #[inline]
    pub fn new(iter: I, length: usize) -> Self {
        Self {
            iter,
            length,
            consumed: 0,
        }
    }

    /// the number of elements in the iterator. Note that this _is not_ the number of runs.
    #[inline]
    pub fn len(&self) -> usize {
        self.length - self.consumed
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<'a, I: Iterator<Item = hybrid_rle::HybridEncoded<'a>>> HybridRleRunsIterator<'a>
    for HybridRleIter<'a, I>
{
    fn number_of_elements(&self) -> usize {
        self.len()
    }
}

impl<'a, I: Iterator<Item = hybrid_rle::HybridEncoded<'a>>> Iterator for HybridRleIter<'a, I> {
    type Item = HybridEncoded<'a>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.consumed == self.length {
            return None;
        };
        let run = self.iter.next()?;

        Some(match run {
            hybrid_rle::HybridEncoded::Bitpacked(pack) => {
                // a pack has at most `pack.len() * 8` bits
                let pack_size = pack.len() * 8;

                let additional = pack_size.min(self.len());

                self.consumed += additional;
                HybridEncoded::Bitmap(pack, additional)
            }
            hybrid_rle::HybridEncoded::Rle(value, length) => {
                let is_set = value[0] == 1;

                let additional = length.min(self.len());

                self.consumed += additional;
                HybridEncoded::Repeated(is_set, additional)
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

/// Type definition for a [`HybridRleIter`] using [`hybrid_rle::Decoder`].
pub type HybridDecoderBitmapIter<'a> = HybridRleIter<'a, hybrid_rle::Decoder<'a>>;

#[derive(Debug)]
enum HybridBooleanState<'a> {
    /// a bitmap
    Bitmap(BitmapIter<'a>),
    /// A repeated item. The first attribute corresponds to whether the value is set
    /// the second attribute corresponds to the number of repetitions.
    Repeated(bool, usize),
}

/// An iterator adapter that maps an iterator of [`HybridEncoded`] into an iterator
/// over [`bool`].
#[derive(Debug)]
pub struct HybridRleBooleanIter<'a, I: Iterator<Item = HybridEncoded<'a>>> {
    iter: I,
    current_run: Option<HybridBooleanState<'a>>,
}

impl<'a, I: Iterator<Item = HybridEncoded<'a>>> HybridRleBooleanIter<'a, I> {
    pub fn new(iter: I) -> Self {
        Self {
            iter,
            current_run: None,
        }
    }
}

impl<'a, I: HybridRleRunsIterator<'a>> Iterator for HybridRleBooleanIter<'a, I> {
    type Item = bool;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(run) = &mut self.current_run {
            match run {
                HybridBooleanState::Bitmap(bitmap) => bitmap.next(),
                HybridBooleanState::Repeated(value, remaining) => {
                    if *remaining == 0 {
                        None
                    } else {
                        *remaining -= 1;
                        Some(*value)
                    }
                }
            }
        } else if let Some(run) = self.iter.next() {
            self.current_run = Some(match run {
                HybridEncoded::Bitmap(bitmap, length) => {
                    HybridBooleanState::Bitmap(BitmapIter::new(bitmap, 0, length))
                }
                HybridEncoded::Repeated(value, length) => {
                    HybridBooleanState::Repeated(value, length)
                }
            });
            self.next()
        } else {
            None
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = self.iter.number_of_elements();
        (exact, Some(exact))
    }
}

/// Type definition for a [`HybridRleBooleanIter`] using [`hybrid_rle::Decoder`].
pub type HybridRleDecoderIter<'a> = HybridRleBooleanIter<'a, HybridDecoderBitmapIter<'a>>;