Skip to main content

vortex_mask/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! A mask is a set of sorted unique positive integers.
5#![deny(missing_docs)]
6
7mod bitops;
8mod eq;
9mod intersect_by_rank;
10
11#[cfg(test)]
12mod tests;
13
14use std::cmp::Ordering;
15use std::fmt::Debug;
16use std::fmt::Formatter;
17use std::ops::Bound;
18use std::ops::RangeBounds;
19use std::sync::Arc;
20use std::sync::OnceLock;
21
22use itertools::Itertools;
23use vortex_buffer::BitBuffer;
24use vortex_buffer::BitBufferMut;
25use vortex_buffer::BitIterator;
26use vortex_buffer::filter::Selection;
27use vortex_error::VortexResult;
28use vortex_error::vortex_panic;
29
30/// Represents a set of values that are all included, all excluded, or some mixture of both.
31pub enum AllOr<T> {
32    /// All values are included.
33    All,
34    /// No values are included.
35    None,
36    /// Some values are included.
37    Some(T),
38}
39
40impl<T> AllOr<T> {
41    /// Returns the `Some` variant of the enum, or a default value.
42    #[inline]
43    pub fn unwrap_or_else<F, G>(self, all_true: F, all_false: G) -> T
44    where
45        F: FnOnce() -> T,
46        G: FnOnce() -> T,
47    {
48        match self {
49            Self::Some(v) => v,
50            AllOr::All => all_true(),
51            AllOr::None => all_false(),
52        }
53    }
54}
55
56impl<T> AllOr<&T> {
57    /// Clone the inner value.
58    #[inline]
59    pub fn cloned(self) -> AllOr<T>
60    where
61        T: Clone,
62    {
63        match self {
64            Self::All => AllOr::All,
65            Self::None => AllOr::None,
66            Self::Some(v) => AllOr::Some(v.clone()),
67        }
68    }
69}
70
71impl<T> Debug for AllOr<T>
72where
73    T: Debug,
74{
75    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76        match self {
77            Self::All => f.write_str("All"),
78            Self::None => f.write_str("None"),
79            Self::Some(v) => f.debug_tuple("Some").field(v).finish(),
80        }
81    }
82}
83
84impl<T> PartialEq for AllOr<T>
85where
86    T: PartialEq,
87{
88    fn eq(&self, other: &Self) -> bool {
89        match (self, other) {
90            (Self::All, Self::All) => true,
91            (Self::None, Self::None) => true,
92            (Self::Some(lhs), Self::Some(rhs)) => lhs == rhs,
93            _ => false,
94        }
95    }
96}
97
98impl<T> Eq for AllOr<T> where T: Eq {}
99
100/// Represents a set of sorted unique positive integers.
101/// If a value is included in a Mask, it's valid.
102///
103/// A [`Mask`] can be constructed from various representations, and converted to various
104/// others. Internally, these are cached.
105#[derive(Clone)]
106#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
107pub enum Mask {
108    /// All values are included.
109    AllTrue(usize),
110    /// No values are included.
111    AllFalse(usize),
112    /// Some values are included, represented as a [`BitBuffer`].
113    Values(MaskValuesRef),
114}
115
116impl Debug for Mask {
117    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
118        match self {
119            Self::AllTrue(len) => write!(f, "All true({len})"),
120            Self::AllFalse(len) => write!(f, "All false({len})"),
121            Self::Values(mask) => write!(f, "{mask:?}"),
122        }
123    }
124}
125
126impl Default for Mask {
127    fn default() -> Self {
128        Self::new_true(0)
129    }
130}
131
132/// Represents the values of a [`Mask`] that contains some true and some false elements.
133#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
134pub struct MaskValues {
135    buffer: BitBuffer,
136
137    // We cached the indices and slices representations, since it can be faster than iterating
138    // the bit-mask over and over again.
139    #[cfg_attr(feature = "serde", serde(skip))]
140    indices: OnceLock<Vec<usize>>,
141    #[cfg_attr(feature = "serde", serde(skip))]
142    slices: OnceLock<Vec<(usize, usize)>>,
143
144    // Pre-computed values.
145    true_count: usize,
146    // i.e., the fraction of values that are true
147    density: f64,
148}
149
150/// A shared reference to [`MaskValues`].
151pub type MaskValuesRef = Arc<MaskValues>;
152
153impl Debug for MaskValues {
154    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
155        write!(f, "true_count={}, ", self.true_count)?;
156        write!(f, "density={}, ", self.density)?;
157        if let Some(v) = self.indices.get() {
158            write!(f, "indices={v:?}, ")?;
159        }
160        if let Some(v) = self.slices.get() {
161            write!(f, "slices={v:?}, ")?;
162        }
163        if f.alternate() {
164            f.write_str("\n")?;
165        }
166        write!(f, "{}", self.buffer)
167    }
168}
169
170impl Mask {
171    /// Create a new Mask with the given length.
172    pub fn new(length: usize, value: bool) -> Self {
173        if value {
174            Self::AllTrue(length)
175        } else {
176            Self::AllFalse(length)
177        }
178    }
179
180    /// Create a new Mask where all values are set.
181    #[inline]
182    pub fn new_true(length: usize) -> Self {
183        Self::AllTrue(length)
184    }
185
186    /// Create a new Mask where no values are set.
187    #[inline]
188    pub fn new_false(length: usize) -> Self {
189        Self::AllFalse(length)
190    }
191
192    /// Create a new [`Mask`] from a [`BitBuffer`].
193    pub fn from_buffer(buffer: BitBuffer) -> Self {
194        let len = buffer.len();
195        let true_count = buffer.true_count();
196
197        if true_count == 0 {
198            return Self::AllFalse(len);
199        }
200        if true_count == len {
201            return Self::AllTrue(len);
202        }
203
204        Self::Values(Arc::new(MaskValues {
205            buffer,
206            indices: Default::default(),
207            slices: Default::default(),
208            true_count,
209            density: true_count as f64 / len as f64,
210        }))
211    }
212
213    /// Create a new [`Mask`] from a [`BitBuffer`] and the ranges of its set bits, which are cached
214    /// on the mask so they need not be recomputed from the buffer.
215    ///
216    /// `slices` must be sorted, non-overlapping `(start, end)` ranges that cover exactly the set
217    /// bits of `buffer`. This is only checked in debug builds.
218    pub fn from_buffer_with_slices(buffer: BitBuffer, slices: Vec<(usize, usize)>) -> Self {
219        let len = buffer.len();
220        #[cfg(debug_assertions)]
221        {
222            Self::check_slices(len, &slices);
223            for &(start, end) in &slices {
224                assert_eq!(
225                    buffer.count_range(start, end),
226                    end - start,
227                    "Slice ({start}, {end}) is not fully set in the buffer"
228                );
229            }
230        }
231
232        let true_count = slices.iter().map(|(start, end)| end - start).sum();
233        debug_assert_eq!(
234            true_count,
235            buffer.true_count(),
236            "Slices must cover every set bit of the buffer"
237        );
238
239        if true_count == 0 {
240            return Self::AllFalse(len);
241        }
242        if true_count == len {
243            return Self::AllTrue(len);
244        }
245
246        Self::Values(Arc::new(MaskValues {
247            buffer,
248            indices: Default::default(),
249            slices: OnceLock::from(slices),
250            true_count,
251            density: true_count as f64 / len as f64,
252        }))
253    }
254
255    /// Create a new [`Mask`] from sorted, unique indices.
256    pub fn from_indices(len: usize, indices: impl IntoIterator<Item = usize>) -> Self {
257        let indices = indices.into_iter().collect::<Vec<_>>();
258        assert!(indices.is_sorted(), "Mask indices must be sorted");
259        assert!(
260            indices.windows(2).all(|w| w[0] != w[1]),
261            "Mask indices must be unique"
262        );
263        let buffer = BitBuffer::from_indices(len, indices.iter().copied());
264        debug_assert_eq!(buffer.len(), len);
265        let true_count = indices.len();
266
267        if true_count == 0 {
268            return Self::AllFalse(len);
269        }
270        if true_count == len {
271            return Self::AllTrue(len);
272        }
273
274        Self::Values(Arc::new(MaskValues {
275            buffer,
276            indices: OnceLock::from(indices),
277            slices: Default::default(),
278            true_count,
279            density: true_count as f64 / len as f64,
280        }))
281    }
282
283    /// Create a new [`Mask`] from an [`IntoIterator<Item = usize>`] of indices to be excluded.
284    ///
285    /// Indices may be in any order and duplicates are ignored.
286    ///
287    /// # Panics
288    ///
289    /// Panics if an index is out of bounds.
290    pub fn from_excluded_indices(len: usize, indices: impl IntoIterator<Item = usize>) -> Self {
291        let mut buf = BitBufferMut::new_set(len);
292        indices.into_iter().for_each(|idx| buf.unset(idx));
293        let buffer = buf.freeze();
294        let true_count = buffer.true_count();
295
296        // Return optimized variants when appropriate
297        if true_count == len {
298            return Self::AllTrue(len);
299        }
300        if true_count == 0 {
301            return Self::AllFalse(len);
302        }
303
304        Self::Values(Arc::new(MaskValues {
305            buffer,
306            indices: Default::default(),
307            slices: Default::default(),
308            true_count,
309            density: true_count as f64 / len as f64,
310        }))
311    }
312
313    /// Create a new [`Mask`] from a [`Vec<(usize, usize)>`] where each range
314    /// represents a contiguous range of true values.
315    pub fn from_slices(len: usize, vec: Vec<(usize, usize)>) -> Self {
316        Self::check_slices(len, &vec);
317        Self::from_slices_unchecked(len, vec)
318    }
319
320    fn from_slices_unchecked(len: usize, slices: Vec<(usize, usize)>) -> Self {
321        #[cfg(debug_assertions)]
322        Self::check_slices(len, &slices);
323
324        let true_count = slices.iter().map(|(b, e)| e - b).sum();
325        if true_count == 0 {
326            return Self::AllFalse(len);
327        }
328        if true_count == len {
329            return Self::AllTrue(len);
330        }
331
332        let mut buf = BitBufferMut::with_capacity(len);
333        let mut cursor = 0;
334        for (start, end) in slices.iter().copied() {
335            buf.append_n(false, start - cursor);
336            buf.append_n(true, end - start);
337            cursor = end;
338        }
339        buf.append_n(false, len - cursor);
340        debug_assert_eq!(buf.len(), len);
341
342        Self::Values(Arc::new(MaskValues {
343            buffer: buf.freeze(),
344            indices: Default::default(),
345            slices: OnceLock::from(slices),
346            true_count,
347            density: true_count as f64 / len as f64,
348        }))
349    }
350
351    #[allow(clippy::inline_always)]
352    #[inline(always)]
353    fn check_slices(len: usize, vec: &[(usize, usize)]) {
354        assert!(vec.iter().all(|&(b, e)| b < e && e <= len));
355        for (first, second) in vec.iter().tuple_windows() {
356            assert!(
357                first.0 < second.0,
358                "Slices must be sorted, got {first:?} and {second:?}"
359            );
360            assert!(
361                first.1 <= second.0,
362                "Slices must be non-overlapping, got {first:?} and {second:?}"
363            );
364        }
365    }
366
367    /// Create a new [`Mask`] from the intersection of two indices slices.
368    pub fn from_intersection_indices(
369        len: usize,
370        lhs: impl Iterator<Item = usize>,
371        rhs: impl Iterator<Item = usize>,
372    ) -> Self {
373        let mut intersection = Vec::with_capacity(len);
374        let mut lhs = lhs.peekable();
375        let mut rhs = rhs.peekable();
376        while let (Some(&l), Some(&r)) = (lhs.peek(), rhs.peek()) {
377            match l.cmp(&r) {
378                Ordering::Less => {
379                    lhs.next();
380                }
381                Ordering::Greater => {
382                    rhs.next();
383                }
384                Ordering::Equal => {
385                    intersection.push(l);
386                    lhs.next();
387                    rhs.next();
388                }
389            }
390        }
391        Self::from_indices(len, intersection)
392    }
393
394    /// Clears the mask of all data. Drops any allocated capacity.
395    pub fn clear(&mut self) {
396        *self = Self::new_false(0);
397    }
398
399    /// Returns the length of the mask (not the number of true values).
400    #[inline]
401    pub fn len(&self) -> usize {
402        match self {
403            Self::AllTrue(len) => *len,
404            Self::AllFalse(len) => *len,
405            Self::Values(values) => values.len(),
406        }
407    }
408
409    /// Returns true if the mask is empty i.e., it's length is 0.
410    #[inline]
411    pub fn is_empty(&self) -> bool {
412        match self {
413            Self::AllTrue(len) => *len == 0,
414            Self::AllFalse(len) => *len == 0,
415            Self::Values(values) => values.is_empty(),
416        }
417    }
418
419    /// Get the true count of the mask.
420    #[inline]
421    pub fn true_count(&self) -> usize {
422        match &self {
423            Self::AllTrue(len) => *len,
424            Self::AllFalse(_) => 0,
425            Self::Values(values) => values.true_count,
426        }
427    }
428
429    /// Get the false count of the mask.
430    #[inline]
431    pub fn false_count(&self) -> usize {
432        match &self {
433            Self::AllTrue(_) => 0,
434            Self::AllFalse(len) => *len,
435            Self::Values(values) => values.buffer.len() - values.true_count,
436        }
437    }
438
439    /// Returns true if all values in the mask are true.
440    #[inline]
441    pub fn all_true(&self) -> bool {
442        match &self {
443            Self::AllTrue(_) => true,
444            Self::AllFalse(0) => true,
445            Self::AllFalse(_) => false,
446            Self::Values(values) => values.buffer.len() == values.true_count,
447        }
448    }
449
450    /// Returns true if all values in the mask are false.
451    #[inline]
452    pub fn all_false(&self) -> bool {
453        self.true_count() == 0
454    }
455
456    /// Return the density of the full mask.
457    #[inline]
458    pub fn density(&self) -> f64 {
459        match &self {
460            Self::AllTrue(_) => 1.0,
461            Self::AllFalse(_) => 0.0,
462            Self::Values(values) => values.density,
463        }
464    }
465
466    /// Returns the boolean value at a given index.
467    ///
468    /// ## Panics
469    ///
470    /// Panics if the index is out of bounds.
471    #[inline]
472    pub fn value(&self, idx: usize) -> bool {
473        match self {
474            Mask::AllTrue(_) => true,
475            Mask::AllFalse(_) => false,
476            Mask::Values(values) => values.buffer.value(idx),
477        }
478    }
479
480    /// Iterate the mask as one `bool` per element, in order.
481    ///
482    /// Unlike repeatedly calling [`Mask::value`], this advances a single cursor rather than
483    /// recomputing the byte/bit offset for every element, and it does not allocate for the
484    /// all-true / all-false variants. Prefer this for sequential per-element scans.
485    #[inline]
486    pub fn iter(&self) -> MaskBoolIter<'_> {
487        match self {
488            Mask::AllTrue(len) => MaskBoolIter::Repeat {
489                value: true,
490                remaining: *len,
491            },
492            Mask::AllFalse(len) => MaskBoolIter::Repeat {
493                value: false,
494                remaining: *len,
495            },
496            Mask::Values(values) => MaskBoolIter::Bits(values.bit_buffer().iter()),
497        }
498    }
499
500    /// Returns the first true index in the mask.
501    pub fn first(&self) -> Option<usize> {
502        match &self {
503            Self::AllTrue(len) => (*len > 0).then_some(0),
504            Self::AllFalse(_) => None,
505            Self::Values(values) => {
506                if let Some(indices) = values.indices.get() {
507                    return indices.first().copied();
508                }
509                if let Some(slices) = values.slices.get() {
510                    return slices.first().map(|(start, _)| *start);
511                }
512                values.buffer.set_indices().next()
513            }
514        }
515    }
516
517    /// Returns the last true index in the mask.
518    pub fn last(&self) -> Option<usize> {
519        match &self {
520            Self::AllTrue(len) => len.checked_sub(1),
521            Self::AllFalse(_) => None,
522            Self::Values(values) => {
523                if let Some(indices) = values.indices.get() {
524                    return indices.last().copied();
525                }
526                if let Some(slices) = values.slices.get() {
527                    return slices.last().map(|(_, end)| end - 1);
528                }
529
530                values.buffer.last_set_index()
531            }
532        }
533    }
534
535    /// Returns the position in the mask of the nth true value.
536    pub fn rank(&self, n: usize) -> usize {
537        if n >= self.true_count() {
538            vortex_panic!(
539                "Rank {n} out of bounds for mask with true count {}",
540                self.true_count()
541            );
542        }
543        match &self {
544            Self::AllTrue(_) => n,
545            Self::AllFalse(_) => unreachable!("no true values in all-false mask"),
546            Self::Values(values) => {
547                if let Some(indices) = values.indices.get() {
548                    return indices[n];
549                }
550
551                values.buffer.select(n).unwrap_or_else(|| {
552                    vortex_panic!(
553                        "Rank {} out of bounds for mask with true count {}",
554                        values.true_count - 1,
555                        values.true_count
556                    )
557                })
558            }
559        }
560    }
561
562    /// Slice the mask.
563    pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
564        let start = match range.start_bound() {
565            Bound::Included(&s) => s,
566            Bound::Excluded(&s) => s + 1,
567            Bound::Unbounded => 0,
568        };
569        let end = match range.end_bound() {
570            Bound::Included(&e) => e + 1,
571            Bound::Excluded(&e) => e,
572            Bound::Unbounded => self.len(),
573        };
574
575        assert!(start <= end);
576        assert!(start <= self.len());
577        assert!(end <= self.len());
578        let len = end - start;
579
580        // Slicing the whole mask is the identity. `Self` is `Arc`-backed, so the clone is cheap
581        // and keeps the cached `indices`/`slices` representations that `from_buffer` would drop.
582        if len == self.len() {
583            return self.clone();
584        }
585
586        match &self {
587            Self::AllTrue(_) => Self::new_true(len),
588            Self::AllFalse(_) => Self::new_false(len),
589            Self::Values(values) => Self::from_buffer(values.buffer.slice(range)),
590        }
591    }
592
593    /// Return the boolean buffer representation of the mask.
594    #[inline]
595    pub fn bit_buffer(&self) -> AllOr<&BitBuffer> {
596        match &self {
597            Self::AllTrue(_) => AllOr::All,
598            Self::AllFalse(_) => AllOr::None,
599            Self::Values(values) => AllOr::Some(&values.buffer),
600        }
601    }
602
603    /// Return a boolean buffer representation of the mask, allocating new buffers for all-true
604    /// and all-false variants.
605    #[inline]
606    pub fn to_bit_buffer(&self) -> BitBuffer {
607        match self {
608            Self::AllTrue(l) => BitBuffer::new_set(*l),
609            Self::AllFalse(l) => BitBuffer::new_unset(*l),
610            Self::Values(values) => values.bit_buffer().clone(),
611        }
612    }
613
614    /// Return a boolean buffer representation of the mask, allocating new buffers for all-true
615    /// and all-false variants.
616    #[inline]
617    pub fn into_bit_buffer(self) -> BitBuffer {
618        match self {
619            Self::AllTrue(l) => BitBuffer::new_set(l),
620            Self::AllFalse(l) => BitBuffer::new_unset(l),
621            Self::Values(values) => Arc::try_unwrap(values)
622                .map(|v| v.into_bit_buffer())
623                .unwrap_or_else(|v| v.bit_buffer().clone()),
624        }
625    }
626
627    /// Return the indices representation of the mask.
628    #[inline]
629    pub fn indices(&self) -> AllOr<&[usize]> {
630        match &self {
631            Self::AllTrue(_) => AllOr::All,
632            Self::AllFalse(_) => AllOr::None,
633            Self::Values(values) => AllOr::Some(values.indices()),
634        }
635    }
636
637    /// Return the slices representation of the mask.
638    #[inline]
639    pub fn slices(&self) -> AllOr<&[(usize, usize)]> {
640        match &self {
641            Self::AllTrue(_) => AllOr::All,
642            Self::AllFalse(_) => AllOr::None,
643            Self::Values(values) => AllOr::Some(values.slices()),
644        }
645    }
646
647    /// Return an iterator over either indices or slices of the mask based on a density threshold.
648    #[inline]
649    pub fn threshold_iter(&self, threshold: f64) -> AllOr<MaskIter<'_>> {
650        match &self {
651            Self::AllTrue(_) => AllOr::All,
652            Self::AllFalse(_) => AllOr::None,
653            Self::Values(values) => AllOr::Some(values.threshold_iter(threshold)),
654        }
655    }
656
657    /// Return [`MaskValues`] if the mask is not all true or all false.
658    #[inline]
659    pub fn values(&self) -> Option<&MaskValues> {
660        if let Self::Values(values) = self {
661            Some(values)
662        } else {
663            None
664        }
665    }
666
667    /// Given monotonically increasing `indices` in [0, n_rows], returns the
668    /// count of valid elements up to each index.
669    ///
670    /// This is O(n_rows), but the per-gap counts are computed with a SIMD
671    /// popcount over the underlying bit buffer rather than walking bit-by-bit.
672    pub fn valid_counts_for_indices(&self, indices: &[usize]) -> Vec<usize> {
673        match self {
674            Self::AllTrue(_) => indices.to_vec(),
675            Self::AllFalse(_) => vec![0; indices.len()],
676            Self::Values(values) => {
677                let buffer = values.bit_buffer();
678                let mut valid_counts = Vec::with_capacity(indices.len());
679                let mut valid_count = 0;
680                let mut prev = 0;
681                for &next_idx in indices {
682                    assert!(next_idx <= buffer.len(), "Row indices exceed array length");
683                    // `indices` is monotonically increasing, so each gap is counted once;
684                    // the total work across all gaps scans the prefix `[0, last_idx)` once.
685                    if next_idx > prev {
686                        valid_count += buffer.count_range(prev, next_idx);
687                        prev = next_idx;
688                    }
689                    valid_counts.push(valid_count);
690                }
691
692                valid_counts
693            }
694        }
695    }
696
697    /// Limit the mask to the first `limit` true values
698    pub fn limit(self, limit: usize) -> Self {
699        // Early return optimization: if we're asking for more true values than the total
700        // length of the mask, then even if all values were true, we couldn't exceed the
701        // limit, so return the original mask unchanged.
702        if self.len() <= limit {
703            return self;
704        }
705
706        match &self {
707            Mask::AllTrue(len) => {
708                Self::from_iter([Self::new_true(limit), Self::new_false(len - limit)])
709            }
710            Mask::AllFalse(_) => self,
711            Mask::Values(mask_values) => {
712                if limit >= mask_values.true_count() {
713                    return self;
714                }
715
716                let existing_buffer = mask_values.bit_buffer();
717
718                let mut new_buffer_builder = BitBufferMut::new_unset(mask_values.len());
719                debug_assert!(limit < mask_values.len());
720
721                for index in existing_buffer.set_indices().take(limit) {
722                    // SAFETY: We checked that `limit` was less than the mask values length,
723                    // therefore `index` must be within the bounds of the bit buffer.
724                    unsafe { new_buffer_builder.set_unchecked(index) }
725                }
726
727                Self::from(new_buffer_builder.freeze())
728            }
729        }
730    }
731
732    /// Concatenate multiple masks together into a single mask.
733    pub fn concat<'a>(masks: impl Iterator<Item = &'a Self>) -> VortexResult<Self> {
734        let masks: Vec<_> = masks.collect();
735        let len = masks.iter().map(|t| t.len()).sum();
736
737        if masks.iter().all(|t| t.all_true()) {
738            return Ok(Mask::AllTrue(len));
739        }
740
741        if masks.iter().all(|t| t.all_false()) {
742            return Ok(Mask::AllFalse(len));
743        }
744
745        let mut builder = BitBufferMut::with_capacity(len);
746
747        for mask in masks {
748            match mask {
749                Mask::AllTrue(n) => builder.append_n(true, *n),
750                Mask::AllFalse(n) => builder.append_n(false, *n),
751                Mask::Values(v) => builder.append_buffer(v.bit_buffer()),
752            }
753        }
754
755        Ok(Mask::from_buffer(builder.freeze()))
756    }
757}
758
759impl MaskValues {
760    /// Returns the length of the mask.
761    #[inline]
762    pub fn len(&self) -> usize {
763        self.buffer.len()
764    }
765
766    /// Returns true if the mask is empty i.e., it's length is 0.
767    #[inline]
768    pub fn is_empty(&self) -> bool {
769        self.buffer.is_empty()
770    }
771
772    /// Returns the density of the mask.
773    #[inline]
774    pub fn density(&self) -> f64 {
775        self.density
776    }
777
778    /// Returns the true count of the mask.
779    #[inline]
780    pub fn true_count(&self) -> usize {
781        self.true_count
782    }
783
784    /// Returns the boolean buffer representation of the mask.
785    #[inline]
786    pub fn bit_buffer(&self) -> &BitBuffer {
787        &self.buffer
788    }
789
790    /// Returns the boolean buffer representation of the mask.
791    #[inline]
792    pub fn into_bit_buffer(self) -> BitBuffer {
793        self.buffer
794    }
795
796    /// Returns the boolean value at a given index.
797    #[inline]
798    pub fn value(&self, index: usize) -> bool {
799        self.buffer.value(index)
800    }
801
802    /// Constructs an indices vector from one of the other representations.
803    pub fn indices(&self) -> &[usize] {
804        self.indices.get_or_init(|| {
805            if self.true_count == 0 {
806                return vec![];
807            }
808
809            if self.true_count == self.len() {
810                return (0..self.len()).collect();
811            }
812
813            if let Some(slices) = self.slices.get() {
814                let mut indices = Vec::with_capacity(self.true_count);
815                indices.extend(slices.iter().flat_map(|(start, end)| *start..*end));
816                debug_assert!(indices.is_sorted());
817                assert_eq!(indices.len(), self.true_count);
818                return indices;
819            }
820
821            let mut indices = Vec::with_capacity(self.true_count);
822            // Word-at-a-time set-bit walk; faster than collecting `set_indices()`,
823            // whose per-`next` iterator state inlines less well (see
824            // `vortex-mask/benches/mask_iteration.rs`).
825            self.buffer.for_each_set_index(|i| indices.push(i));
826            debug_assert!(indices.is_sorted());
827            assert_eq!(indices.len(), self.true_count);
828            indices
829        })
830    }
831
832    /// Returns cached index positions when this mask already has them materialized.
833    ///
834    /// Unlike [`Self::indices`], this does not build the index vector from another
835    /// representation.
836    #[inline]
837    pub fn cached_indices(&self) -> Option<&[usize]> {
838        self.indices.get().map(Vec::as_slice)
839    }
840
841    /// Constructs a slices vector from one of the other representations.
842    #[inline]
843    pub fn slices(&self) -> &[(usize, usize)] {
844        self.slices.get_or_init(|| {
845            if self.true_count == self.len() {
846                return vec![(0, self.len())];
847            }
848
849            self.buffer.set_slices().collect()
850        })
851    }
852
853    /// Returns cached true-value ranges when this mask already has them materialized.
854    ///
855    /// Unlike [`Self::slices`], this does not build the slice vector from another
856    /// representation.
857    #[inline]
858    pub fn cached_slices(&self) -> Option<&[(usize, usize)]> {
859        self.slices.get().map(Vec::as_slice)
860    }
861
862    /// Return an iterator over either indices or slices of the mask based on a density threshold.
863    #[inline]
864    pub fn threshold_iter(&self, threshold: f64) -> MaskIter<'_> {
865        if self.density >= threshold {
866            MaskIter::Slices(self.slices())
867        } else {
868            MaskIter::Indices(self.indices())
869        }
870    }
871
872    /// Returns the representation of the mask that is cheapest to filter with, for
873    /// [`vortex_buffer::filter`].
874    ///
875    /// This uses the cached slices if there is one slice or their runs average at least 8 values,
876    /// then the cached indices if the density is at most 0.5, and otherwise the bitmap. It does
877    /// not build a representation that is not cached.
878    pub fn selection(&self) -> Selection<'_> {
879        // SAFETY: the mask validated its cached slices and indices when it created them, and it
880        // holds the true count of its bitmap.
881        unsafe {
882            if let Some(slices) = self.useful_cached_slices() {
883                Selection::from_slices_unchecked(self.len(), slices, self.true_count)
884            } else if let Some(indices) = self.useful_cached_indices() {
885                Selection::from_indices_unchecked(self.len(), indices)
886            } else {
887                Selection::from_bitmap_unchecked(&self.buffer, self.true_count)
888            }
889        }
890    }
891
892    fn useful_cached_slices(&self) -> Option<&[(usize, usize)]> {
893        self.cached_slices().filter(|slices| {
894            slices.len() == 1 || self.true_count / slices.len() >= SELECTION_MIN_AVERAGE_RUN_LEN
895        })
896    }
897
898    fn useful_cached_indices(&self) -> Option<&[usize]> {
899        if self.density <= SELECTION_INDICES_MAX_DENSITY {
900            self.cached_indices()
901        } else {
902            None
903        }
904    }
905}
906
907/// The smallest average run length for which [`MaskValues::selection`] uses the cached slices.
908const SELECTION_MIN_AVERAGE_RUN_LEN: usize = 8;
909
910/// The largest density for which [`MaskValues::selection`] uses the cached indices.
911const SELECTION_INDICES_MAX_DENSITY: f64 = 0.5;
912
913/// Iterator over the indices or slices of a mask.
914pub enum MaskIter<'a> {
915    /// Slice of pre-cached indices of a mask.
916    Indices(&'a [usize]),
917    /// Slice of pre-cached slices of a mask.
918    Slices(&'a [(usize, usize)]),
919}
920
921/// Iterator yielding one `bool` per element of a [`Mask`], in order.
922///
923/// Created by [`Mask::iter`].
924pub enum MaskBoolIter<'a> {
925    /// An all-true or all-false run.
926    Repeat {
927        /// The constant value yielded by every element of the run.
928        value: bool,
929        /// The number of elements still to yield.
930        remaining: usize,
931    },
932    /// Per-element bits of a [`Mask::Values`] mask.
933    Bits(BitIterator<'a>),
934}
935
936impl Iterator for MaskBoolIter<'_> {
937    type Item = bool;
938
939    #[inline]
940    fn next(&mut self) -> Option<Self::Item> {
941        match self {
942            Self::Repeat { remaining: 0, .. } => None,
943            Self::Repeat { value, remaining } => {
944                *remaining -= 1;
945                Some(*value)
946            }
947            Self::Bits(bits) => bits.next(),
948        }
949    }
950
951    #[inline]
952    fn size_hint(&self) -> (usize, Option<usize>) {
953        let remaining = match self {
954            Self::Repeat { remaining, .. } => *remaining,
955            Self::Bits(bits) => bits.len(),
956        };
957        (remaining, Some(remaining))
958    }
959}
960
961impl ExactSizeIterator for MaskBoolIter<'_> {}
962
963impl From<BitBuffer> for Mask {
964    fn from(value: BitBuffer) -> Self {
965        Self::from_buffer(value)
966    }
967}
968
969impl FromIterator<bool> for Mask {
970    #[inline]
971    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
972        Self::from_buffer(BitBuffer::from_iter(iter))
973    }
974}
975
976impl FromIterator<Mask> for Mask {
977    fn from_iter<T: IntoIterator<Item = Mask>>(iter: T) -> Self {
978        let masks = iter
979            .into_iter()
980            .filter(|m| !m.is_empty())
981            .collect::<Vec<_>>();
982        let total_length = masks.iter().map(|v| v.len()).sum();
983
984        // If they're all valid, then return a single validity.
985        if masks.iter().all(|v| v.all_true()) {
986            return Self::AllTrue(total_length);
987        }
988        // If they're all invalid, then return a single invalidity.
989        if masks.iter().all(|v| v.all_false()) {
990            return Self::AllFalse(total_length);
991        }
992
993        // Else, construct the boolean buffer
994        let mut buffer = BitBufferMut::with_capacity(total_length);
995        for mask in masks {
996            match mask {
997                Mask::AllTrue(count) => buffer.append_n(true, count),
998                Mask::AllFalse(count) => buffer.append_n(false, count),
999                Mask::Values(values) => {
1000                    buffer.append_buffer(values.bit_buffer());
1001                }
1002            };
1003        }
1004        Self::from_buffer(buffer.freeze())
1005    }
1006}