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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use std::collections::VecDeque;

use crate::error::Error;
use crate::{encoding::hybrid_rle::BitmapIter, indexes::Interval};

use super::{HybridDecoderBitmapIter, HybridEncoded};

/// Type definition of a [`FilteredHybridBitmapIter`] of [`HybridDecoderBitmapIter`].
pub type FilteredHybridRleDecoderIter<'a> =
    FilteredHybridBitmapIter<'a, HybridDecoderBitmapIter<'a>>;

/// The decoding state of the hybrid-RLE decoder with a maximum definition level of 1
/// that can supports skipped runs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilteredHybridEncoded<'a> {
    /// a bitmap (values, offset, length, skipped_set)
    Bitmap {
        values: &'a [u8],
        offset: usize,
        length: usize,
    },
    Repeated {
        is_set: bool,
        length: usize,
    },
    /// When the run was skipped - contains the number of set values on the skipped run
    Skipped(usize),
}

fn is_set_count(values: &[u8], offset: usize, length: usize) -> usize {
    BitmapIter::new(values, offset, length)
        .filter(|x| *x)
        .count()
}

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

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

/// An [`Iterator`] adapter over [`HybridEncoded`] that yields [`FilteredHybridEncoded`].
///
/// This iterator adapter is used in combination with
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilteredHybridBitmapIter<'a, I: Iterator<Item = Result<HybridEncoded<'a>, Error>>> {
    iter: I,
    current: Option<(HybridEncoded<'a>, usize)>,
    // a run may end in the middle of an interval, in which case we must
    // split the interval in parts. This tracks the current interval being computed
    current_interval: Option<Interval>,
    selected_rows: VecDeque<Interval>,
    current_items_in_runs: usize,

    total_items: usize,
}

impl<'a, I: Iterator<Item = Result<HybridEncoded<'a>, Error>>> FilteredHybridBitmapIter<'a, I> {
    pub fn new(iter: I, selected_rows: VecDeque<Interval>) -> Self {
        let total_items = selected_rows.iter().map(|x| x.length).sum();
        Self {
            iter,
            current: None,
            current_interval: None,
            selected_rows,
            current_items_in_runs: 0,
            total_items,
        }
    }

    fn advance_current_interval(&mut self, length: usize) {
        if let Some(interval) = &mut self.current_interval {
            interval.start += length;
            interval.length -= length;
            self.total_items -= length;
        }
    }

    /// Returns the number of elements remaining. Note that each run
    /// of the iterator contains more than one element - this is is _not_ equivalent to size_hint.
    pub fn len(&self) -> usize {
        self.total_items
    }

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

impl<'a, I: Iterator<Item = Result<HybridEncoded<'a>, Error>>> Iterator
    for FilteredHybridBitmapIter<'a, I>
{
    type Item = Result<FilteredHybridEncoded<'a>, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        let interval = if let Some(interval) = self.current_interval {
            interval
        } else {
            self.current_interval = self.selected_rows.pop_front();
            self.current_interval?; // case where iteration finishes
            return self.next();
        };

        let (run, offset) = if let Some((run, offset)) = self.current {
            (run, offset)
        } else {
            // a new run
            let run = self.iter.next()?; // no run => something wrong since intervals should only slice items up all runs' length
            match run {
                Ok(run) => {
                    self.current = Some((run, 0));
                }
                Err(e) => return Some(Err(e)),
            }
            return self.next();
        };

        // one of three things can happen:
        // * the start of the interval is not aligned wirh the start of the run => issue a `Skipped` and advance the run / next run
        // * the run contains this interval => consume the interval and keep the run
        // * the run contains part of this interval => consume the run and keep the interval

        match run {
            HybridEncoded::Repeated(is_set, full_run_length) => {
                let run_length = full_run_length - offset;
                // interval.start is from the start of the first run; discount `current_items_in_runs`
                // to get the start from the current run's offset
                let interval_start = interval.start - self.current_items_in_runs;

                if interval_start > 0 {
                    // we need to skip values from the run
                    let to_skip = interval_start;

                    // we only skip up to a run (yield a single skip per multiple runs)
                    let max_skip = full_run_length - offset;
                    let to_skip = to_skip.min(max_skip);

                    let set = if is_set { to_skip } else { 0 };

                    self.current_items_in_runs += to_skip;

                    self.current = if to_skip == max_skip {
                        None
                    } else {
                        Some((run, offset + to_skip))
                    };

                    return Some(Ok(FilteredHybridEncoded::Skipped(set)));
                };

                // slice the bitmap according to current interval
                // note that interval start is from the start of the first run.
                let new_offset = offset + interval_start;

                if interval_start > run_length {
                    let set = if is_set { run_length } else { 0 };

                    self.advance_current_interval(run_length);
                    self.current_items_in_runs += run_length;
                    self.current = None;
                    Some(Ok(FilteredHybridEncoded::Skipped(set)))
                } else {
                    let length = if run_length > interval.length {
                        // interval is fully consumed
                        self.current_items_in_runs += interval.length;

                        // fetch next interval
                        self.total_items -= interval.length;
                        self.current_interval = self.selected_rows.pop_front();

                        self.current = Some((run, offset + interval.length));

                        interval.length
                    } else {
                        // the run is consumed and the interval is shortened accordingly
                        self.current_items_in_runs += run_length;

                        // the interval may cover two runs; shorten the length
                        // to its maximum allowed for this run
                        let length = run_length.min(full_run_length - new_offset);

                        self.advance_current_interval(length);

                        self.current = None;
                        length
                    };
                    Some(Ok(FilteredHybridEncoded::Repeated { is_set, length }))
                }
            }
            HybridEncoded::Bitmap(values, full_run_length) => {
                let run_length = full_run_length - offset;
                // interval.start is from the start of the first run; discount `current_items_in_runs`
                // to get the start from the current run's offset
                let interval_start = interval.start - self.current_items_in_runs;

                if interval_start > 0 {
                    // we need to skip values from the run
                    let to_skip = interval_start;

                    // we only skip up to a run (yield a single skip per multiple runs)
                    let max_skip = full_run_length - offset;
                    let to_skip = to_skip.min(max_skip);

                    let set = is_set_count(values, offset, to_skip);

                    self.current_items_in_runs += to_skip;

                    self.current = if to_skip == max_skip {
                        None
                    } else {
                        Some((run, offset + to_skip))
                    };

                    return Some(Ok(FilteredHybridEncoded::Skipped(set)));
                };

                // slice the bitmap according to current interval
                // note that interval start is from the start of the first run.
                let new_offset = offset + interval_start;

                if interval_start > run_length {
                    let set = is_set_count(values, offset, full_run_length);

                    self.advance_current_interval(run_length);
                    self.current_items_in_runs += run_length;
                    self.current = None;
                    Some(Ok(FilteredHybridEncoded::Skipped(set)))
                } else {
                    let length = if run_length > interval.length {
                        // interval is fully consumed
                        self.current_items_in_runs += interval.length;

                        // fetch next interval
                        self.total_items -= interval.length;
                        self.current_interval = self.selected_rows.pop_front();

                        self.current = Some((run, offset + interval.length));

                        interval.length
                    } else {
                        // the run is consumed and the interval is shortened accordingly
                        self.current_items_in_runs += run_length;

                        // the interval may cover two runs; shorten the length
                        // to its maximum allowed for this run
                        let length = run_length.min(full_run_length - new_offset);

                        self.advance_current_interval(length);

                        self.current = None;
                        length
                    };
                    Some(Ok(FilteredHybridEncoded::Bitmap {
                        values,
                        offset: new_offset,
                        length,
                    }))
                }
            }
        }
    }
}