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