lance_core/utils/
mask.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4use std::collections::HashSet;
5use std::io::Write;
6use std::ops::RangeBounds;
7use std::{collections::BTreeMap, io::Read};
8
9use arrow_array::{Array, BinaryArray, GenericBinaryArray};
10use arrow_buffer::{Buffer, NullBuffer, OffsetBuffer};
11use byteorder::{ReadBytesExt, WriteBytesExt};
12use deepsize::DeepSizeOf;
13use roaring::{MultiOps, RoaringBitmap};
14
15use crate::Result;
16
17use super::address::RowAddress;
18
19/// A row id mask to select or deselect particular row ids
20///
21/// If both the allow_list and the block_list are Some then the only selected
22/// row ids are those that are in the allow_list but not in the block_list
23/// (the block_list takes precedence)
24///
25/// If both the allow_list and the block_list are None (the default) then
26/// all row ids are selected
27#[derive(Clone, Debug, Default, DeepSizeOf)]
28pub struct RowIdMask {
29    /// If Some then only these row ids are selected
30    pub allow_list: Option<RowIdTreeMap>,
31    /// If Some then these row ids are not selected.
32    pub block_list: Option<RowIdTreeMap>,
33}
34
35impl RowIdMask {
36    // Create a mask allowing all rows, this is an alias for [default]
37    pub fn all_rows() -> Self {
38        Self::default()
39    }
40
41    // Create a mask that doesn't allow anything
42    pub fn allow_nothing() -> Self {
43        Self {
44            allow_list: Some(RowIdTreeMap::new()),
45            block_list: None,
46        }
47    }
48
49    // Create a mask from an allow list
50    pub fn from_allowed(allow_list: RowIdTreeMap) -> Self {
51        Self {
52            allow_list: Some(allow_list),
53            block_list: None,
54        }
55    }
56
57    // Create a mask from a block list
58    pub fn from_block(block_list: RowIdTreeMap) -> Self {
59        Self {
60            allow_list: None,
61            block_list: Some(block_list),
62        }
63    }
64
65    /// True if the row_id is selected by the mask, false otherwise
66    pub fn selected(&self, row_id: u64) -> bool {
67        match (&self.allow_list, &self.block_list) {
68            (None, None) => true,
69            (Some(allow_list), None) => allow_list.contains(row_id),
70            (None, Some(block_list)) => !block_list.contains(row_id),
71            (Some(allow_list), Some(block_list)) => {
72                allow_list.contains(row_id) && !block_list.contains(row_id)
73            }
74        }
75    }
76
77    /// Return the indices of the input row ids that were valid
78    pub fn selected_indices<'a>(&self, row_ids: impl Iterator<Item = &'a u64> + 'a) -> Vec<u64> {
79        let enumerated_ids = row_ids.enumerate();
80        match (&self.block_list, &self.allow_list) {
81            (Some(block_list), Some(allow_list)) => {
82                // Only take rows that are both in the allow list and not in the block list
83                enumerated_ids
84                    .filter(|(_, row_id)| {
85                        !block_list.contains(**row_id) && allow_list.contains(**row_id)
86                    })
87                    .map(|(idx, _)| idx as u64)
88                    .collect()
89            }
90            (Some(block_list), None) => {
91                // Take rows that are not in the block list
92                enumerated_ids
93                    .filter(|(_, row_id)| !block_list.contains(**row_id))
94                    .map(|(idx, _)| idx as u64)
95                    .collect()
96            }
97            (None, Some(allow_list)) => {
98                // Take rows that are in the allow list
99                enumerated_ids
100                    .filter(|(_, row_id)| allow_list.contains(**row_id))
101                    .map(|(idx, _)| idx as u64)
102                    .collect()
103            }
104            (None, None) => {
105                // We should not encounter this case because callers should
106                // check is_empty first.
107                panic!("selected_indices called but prefilter has nothing to filter with")
108            }
109        }
110    }
111
112    /// Also block the given ids
113    pub fn also_block(self, block_list: RowIdTreeMap) -> Self {
114        if block_list.is_empty() {
115            return self;
116        }
117        if let Some(existing) = self.block_list {
118            Self {
119                block_list: Some(existing | block_list),
120                allow_list: self.allow_list,
121            }
122        } else {
123            Self {
124                block_list: Some(block_list),
125                allow_list: self.allow_list,
126            }
127        }
128    }
129
130    /// Also allow the given ids
131    pub fn also_allow(self, allow_list: RowIdTreeMap) -> Self {
132        if let Some(existing) = self.allow_list {
133            Self {
134                block_list: self.block_list,
135                allow_list: Some(existing | allow_list),
136            }
137        } else {
138            Self {
139                block_list: self.block_list,
140                // allow_list = None means "all rows allowed" and so allowing
141                //              more rows is meaningless
142                allow_list: None,
143            }
144        }
145    }
146
147    /// Convert a mask into an arrow array
148    ///
149    /// A row id mask is not very arrow-compatible.  We can't make it a batch with
150    /// two columns because the block list and allow list will have different lengths.  Also,
151    /// there is no Arrow type for compressed bitmaps.
152    ///
153    /// However, we need to shove it into some kind of Arrow container to pass it along the
154    /// datafusion stream.  Perhaps, in the future, we can add row id masks as first class
155    /// types in datafusion, and this can be passed along as a mask / selection vector.
156    ///
157    /// We serialize this as a variable length binary array with two items.  The first item
158    /// is the block list and the second item is the allow list.
159    pub fn into_arrow(&self) -> Result<BinaryArray> {
160        let block_list_length = self
161            .block_list
162            .as_ref()
163            .map(|bl| bl.serialized_size())
164            .unwrap_or(0);
165        let allow_list_length = self
166            .allow_list
167            .as_ref()
168            .map(|al| al.serialized_size())
169            .unwrap_or(0);
170        let lengths = vec![block_list_length, allow_list_length];
171        let offsets = OffsetBuffer::from_lengths(lengths);
172        let mut value_bytes = vec![0; block_list_length + allow_list_length];
173        let mut validity = vec![false, false];
174        if let Some(block_list) = &self.block_list {
175            validity[0] = true;
176            block_list.serialize_into(&mut value_bytes[0..])?;
177        }
178        if let Some(allow_list) = &self.allow_list {
179            validity[1] = true;
180            allow_list.serialize_into(&mut value_bytes[block_list_length..])?;
181        }
182        let values = Buffer::from(value_bytes);
183        let nulls = NullBuffer::from(validity);
184        Ok(BinaryArray::try_new(offsets, values, Some(nulls))?)
185    }
186
187    /// Deserialize a row id mask from Arrow
188    pub fn from_arrow(array: &GenericBinaryArray<i32>) -> Result<Self> {
189        let block_list = if array.is_null(0) {
190            None
191        } else {
192            Some(RowIdTreeMap::deserialize_from(array.value(0)))
193        }
194        .transpose()?;
195
196        let allow_list = if array.is_null(1) {
197            None
198        } else {
199            Some(RowIdTreeMap::deserialize_from(array.value(1)))
200        }
201        .transpose()?;
202        Ok(Self {
203            block_list,
204            allow_list,
205        })
206    }
207}
208
209impl std::ops::Not for RowIdMask {
210    type Output = Self;
211
212    fn not(self) -> Self::Output {
213        Self {
214            block_list: self.allow_list,
215            allow_list: self.block_list,
216        }
217    }
218}
219
220impl std::ops::BitAnd for RowIdMask {
221    type Output = Self;
222
223    fn bitand(self, rhs: Self) -> Self::Output {
224        let block_list = match (self.block_list, rhs.block_list) {
225            (None, None) => None,
226            (Some(lhs), None) => Some(lhs),
227            (None, Some(rhs)) => Some(rhs),
228            (Some(lhs), Some(rhs)) => Some(lhs | rhs),
229        };
230        let allow_list = match (self.allow_list, rhs.allow_list) {
231            (None, None) => None,
232            (Some(lhs), None) => Some(lhs),
233            (None, Some(rhs)) => Some(rhs),
234            (Some(lhs), Some(rhs)) => Some(lhs & rhs),
235        };
236        Self {
237            block_list,
238            allow_list,
239        }
240    }
241}
242
243impl std::ops::BitOr for RowIdMask {
244    type Output = Self;
245
246    fn bitor(self, rhs: Self) -> Self::Output {
247        let block_list = match (self.block_list, rhs.block_list) {
248            (None, None) => None,
249            (Some(lhs), None) => Some(lhs),
250            (None, Some(rhs)) => Some(rhs),
251            (Some(lhs), Some(rhs)) => Some(lhs & rhs),
252        };
253        let allow_list = match (self.allow_list, rhs.allow_list) {
254            (None, None) => None,
255            // Remember that an allow list of None means "all rows" and
256            // so "all rows" | "some rows" is always "all rows"
257            (Some(_), None) => None,
258            (None, Some(_)) => None,
259            (Some(lhs), Some(rhs)) => Some(lhs | rhs),
260        };
261        Self {
262            block_list,
263            allow_list,
264        }
265    }
266}
267
268/// A collection of row ids.
269///
270/// These row ids may either be stable-style (where they can be an incrementing
271/// u64 sequence) or address style, where they are a fragment id and a row offset.
272/// When address style, this supports setting entire fragments as selected,
273/// without needing to enumerate all the ids in the fragment.
274///
275/// This is similar to a [RoaringTreemap] but it is optimized for the case where
276/// entire fragments are selected or deselected.
277#[derive(Clone, Debug, Default, PartialEq, DeepSizeOf)]
278pub struct RowIdTreeMap {
279    /// The contents of the set. If there is a pair (k, Full) then the entire
280    /// fragment k is selected. If there is a pair (k, Partial(v)) then the
281    /// fragment k has the selected rows in v.
282    inner: BTreeMap<u32, RowIdSelection>,
283}
284
285#[derive(Clone, Debug, PartialEq)]
286enum RowIdSelection {
287    Full,
288    Partial(RoaringBitmap),
289}
290
291impl DeepSizeOf for RowIdSelection {
292    fn deep_size_of_children(&self, _context: &mut deepsize::Context) -> usize {
293        match self {
294            Self::Full => 0,
295            Self::Partial(bitmap) => bitmap.serialized_size(),
296        }
297    }
298}
299
300impl RowIdSelection {
301    fn union_all(selections: &[&Self]) -> Self {
302        let mut is_full = false;
303
304        let res = Self::Partial(
305            selections
306                .iter()
307                .filter_map(|selection| match selection {
308                    Self::Full => {
309                        is_full = true;
310                        None
311                    }
312                    Self::Partial(bitmap) => Some(bitmap),
313                })
314                .union(),
315        );
316
317        if is_full {
318            Self::Full
319        } else {
320            res
321        }
322    }
323}
324
325impl RowIdTreeMap {
326    /// Create an empty set
327    pub fn new() -> Self {
328        Self::default()
329    }
330
331    pub fn is_empty(&self) -> bool {
332        self.inner.is_empty()
333    }
334
335    /// The number of rows in the map
336    ///
337    /// If there are any "full fragment" items then this is unknown and None is returned
338    pub fn len(&self) -> Option<u64> {
339        self.inner
340            .values()
341            .map(|row_id_selection| match row_id_selection {
342                RowIdSelection::Full => None,
343                RowIdSelection::Partial(indices) => Some(indices.len()),
344            })
345            .try_fold(0_u64, |acc, next| next.map(|next| next + acc))
346    }
347
348    /// An iterator of row ids
349    ///
350    /// If there are any "full fragment" items then this can't be calculated and None
351    /// is returned
352    pub fn row_ids(&self) -> Option<impl Iterator<Item = RowAddress> + '_> {
353        let inner_iters = self
354            .inner
355            .iter()
356            .filter_map(|(frag_id, row_id_selection)| match row_id_selection {
357                RowIdSelection::Full => None,
358                RowIdSelection::Partial(bitmap) => Some(
359                    bitmap
360                        .iter()
361                        .map(|row_offset| RowAddress::new_from_parts(*frag_id, row_offset)),
362                ),
363            })
364            .collect::<Vec<_>>();
365        if inner_iters.len() != self.inner.len() {
366            None
367        } else {
368            Some(inner_iters.into_iter().flatten())
369        }
370    }
371
372    /// Insert a single value into the set
373    ///
374    /// Returns true if the value was not already in the set.
375    ///
376    /// ```rust
377    /// use lance_core::utils::mask::RowIdTreeMap;
378    ///
379    /// let mut set = RowIdTreeMap::new();
380    /// assert_eq!(set.insert(10), true);
381    /// assert_eq!(set.insert(10), false);
382    /// assert_eq!(set.contains(10), true);
383    /// ```
384    pub fn insert(&mut self, value: u64) -> bool {
385        let fragment = (value >> 32) as u32;
386        let row_addr = value as u32;
387        match self.inner.get_mut(&fragment) {
388            None => {
389                let mut set = RoaringBitmap::new();
390                set.insert(row_addr);
391                self.inner.insert(fragment, RowIdSelection::Partial(set));
392                true
393            }
394            Some(RowIdSelection::Full) => false,
395            Some(RowIdSelection::Partial(set)) => set.insert(row_addr),
396        }
397    }
398
399    /// Insert a range of values into the set
400    pub fn insert_range<R: RangeBounds<u64>>(&mut self, range: R) -> u64 {
401        // Separate the start and end into high and low bits.
402        let (mut start_high, mut start_low) = match range.start_bound() {
403            std::ops::Bound::Included(&start) => ((start >> 32) as u32, start as u32),
404            std::ops::Bound::Excluded(&start) => {
405                let start = start.saturating_add(1);
406                ((start >> 32) as u32, start as u32)
407            }
408            std::ops::Bound::Unbounded => (0, 0),
409        };
410
411        let (end_high, end_low) = match range.end_bound() {
412            std::ops::Bound::Included(&end) => ((end >> 32) as u32, end as u32),
413            std::ops::Bound::Excluded(&end) => {
414                let end = end.saturating_sub(1);
415                ((end >> 32) as u32, end as u32)
416            }
417            std::ops::Bound::Unbounded => (u32::MAX, u32::MAX),
418        };
419
420        let mut count = 0;
421
422        while start_high <= end_high {
423            let start = start_low;
424            let end = if start_high == end_high {
425                end_low
426            } else {
427                u32::MAX
428            };
429            let fragment = start_high;
430            match self.inner.get_mut(&fragment) {
431                None => {
432                    let mut set = RoaringBitmap::new();
433                    count += set.insert_range(start..=end);
434                    self.inner.insert(fragment, RowIdSelection::Partial(set));
435                }
436                Some(RowIdSelection::Full) => {}
437                Some(RowIdSelection::Partial(set)) => {
438                    count += set.insert_range(start..=end);
439                }
440            }
441            start_high += 1;
442            start_low = 0;
443        }
444
445        count
446    }
447
448    /// Add a bitmap for a single fragment
449    pub fn insert_bitmap(&mut self, fragment: u32, bitmap: RoaringBitmap) {
450        self.inner.insert(fragment, RowIdSelection::Partial(bitmap));
451    }
452
453    /// Add a whole fragment to the set
454    pub fn insert_fragment(&mut self, fragment_id: u32) {
455        self.inner.insert(fragment_id, RowIdSelection::Full);
456    }
457
458    /// Returns whether the set contains the given value
459    pub fn contains(&self, value: u64) -> bool {
460        let upper = (value >> 32) as u32;
461        let lower = value as u32;
462        match self.inner.get(&upper) {
463            None => false,
464            Some(RowIdSelection::Full) => true,
465            Some(RowIdSelection::Partial(fragment_set)) => fragment_set.contains(lower),
466        }
467    }
468
469    pub fn remove(&mut self, value: u64) -> bool {
470        let upper = (value >> 32) as u32;
471        let lower = value as u32;
472        match self.inner.get_mut(&upper) {
473            None => false,
474            Some(RowIdSelection::Full) => {
475                let mut set = RoaringBitmap::full();
476                set.remove(lower);
477                self.inner.insert(upper, RowIdSelection::Partial(set));
478                true
479            }
480            Some(RowIdSelection::Partial(lower_set)) => {
481                let removed = lower_set.remove(lower);
482                if lower_set.is_empty() {
483                    self.inner.remove(&upper);
484                }
485                removed
486            }
487        }
488    }
489
490    pub fn retain_fragments(&mut self, frag_ids: impl IntoIterator<Item = u32>) {
491        let frag_id_set = frag_ids.into_iter().collect::<HashSet<_>>();
492        self.inner
493            .retain(|frag_id, _| frag_id_set.contains(frag_id));
494    }
495
496    /// Compute the serialized size of the set.
497    pub fn serialized_size(&self) -> usize {
498        // Starts at 4 because of the u32 num_entries
499        let mut size = 4;
500        for set in self.inner.values() {
501            // Each entry is 8 bytes for the fragment id and the bitmap size
502            size += 8;
503            if let RowIdSelection::Partial(set) = set {
504                size += set.serialized_size();
505            }
506        }
507        size
508    }
509
510    /// Serialize the set into the given buffer
511    ///
512    /// The serialization format is not stable.
513    ///
514    /// The serialization format is:
515    /// * u32: num_entries
516    ///
517    /// for each entry:
518    ///   * u32: fragment_id
519    ///   * u32: bitmap size
520    ///   * [u8]: bitmap
521    /// If bitmap size is zero then the entire fragment is selected.
522    pub fn serialize_into<W: Write>(&self, mut writer: W) -> Result<()> {
523        writer.write_u32::<byteorder::LittleEndian>(self.inner.len() as u32)?;
524        for (fragment, set) in &self.inner {
525            writer.write_u32::<byteorder::LittleEndian>(*fragment)?;
526            if let RowIdSelection::Partial(set) = set {
527                writer.write_u32::<byteorder::LittleEndian>(set.serialized_size() as u32)?;
528                set.serialize_into(&mut writer)?;
529            } else {
530                writer.write_u32::<byteorder::LittleEndian>(0)?;
531            }
532        }
533        Ok(())
534    }
535
536    /// Deserialize the set from the given buffer
537    pub fn deserialize_from<R: Read>(mut reader: R) -> Result<Self> {
538        let num_entries = reader.read_u32::<byteorder::LittleEndian>()?;
539        let mut inner = BTreeMap::new();
540        for _ in 0..num_entries {
541            let fragment = reader.read_u32::<byteorder::LittleEndian>()?;
542            let bitmap_size = reader.read_u32::<byteorder::LittleEndian>()?;
543            if bitmap_size == 0 {
544                inner.insert(fragment, RowIdSelection::Full);
545            } else {
546                let mut buffer = vec![0; bitmap_size as usize];
547                reader.read_exact(&mut buffer)?;
548                let set = RoaringBitmap::deserialize_from(&buffer[..])?;
549                inner.insert(fragment, RowIdSelection::Partial(set));
550            }
551        }
552        Ok(Self { inner })
553    }
554
555    pub fn union_all(maps: &[&Self]) -> Self {
556        let mut new_map = BTreeMap::new();
557
558        for map in maps {
559            for (fragment, selection) in &map.inner {
560                new_map
561                    .entry(fragment)
562                    // I hate this allocation, but I can't think of a better way
563                    .or_insert_with(|| Vec::with_capacity(maps.len()))
564                    .push(selection);
565            }
566        }
567
568        let new_map = new_map
569            .into_iter()
570            .map(|(&fragment, selections)| (fragment, RowIdSelection::union_all(&selections)))
571            .collect();
572
573        Self { inner: new_map }
574    }
575}
576
577impl std::ops::BitOr<Self> for RowIdTreeMap {
578    type Output = Self;
579
580    fn bitor(mut self, rhs: Self) -> Self::Output {
581        self |= rhs;
582        self
583    }
584}
585
586impl std::ops::BitOrAssign<Self> for RowIdTreeMap {
587    fn bitor_assign(&mut self, rhs: Self) {
588        for (fragment, rhs_set) in &rhs.inner {
589            match self.inner.get_mut(fragment) {
590                None => {
591                    self.inner.insert(*fragment, rhs_set.clone());
592                }
593                Some(RowIdSelection::Full) => {
594                    // If the fragment is already selected then there is nothing to do
595                }
596                Some(RowIdSelection::Partial(lhs_set)) => {
597                    if let RowIdSelection::Partial(rhs_set) = rhs_set {
598                        *lhs_set |= rhs_set;
599                    }
600                }
601            }
602        }
603    }
604}
605
606impl std::ops::BitAnd<Self> for RowIdTreeMap {
607    type Output = Self;
608
609    fn bitand(mut self, rhs: Self) -> Self::Output {
610        self &= rhs;
611        self
612    }
613}
614
615impl std::ops::BitAndAssign<Self> for RowIdTreeMap {
616    fn bitand_assign(&mut self, rhs: Self) {
617        // Remove fragment that aren't on the RHS
618        self.inner
619            .retain(|fragment, _| rhs.inner.contains_key(fragment));
620
621        // For fragments that are on the RHS, intersect the bitmaps
622        for (fragment, mut lhs_set) in &mut self.inner {
623            match (&mut lhs_set, rhs.inner.get(fragment)) {
624                (_, None) => {} // Already handled by retain
625                (_, Some(RowIdSelection::Full)) => {
626                    // Everything selected on RHS, so can leave LHS untouched.
627                }
628                (RowIdSelection::Partial(lhs_set), Some(RowIdSelection::Partial(rhs_set))) => {
629                    *lhs_set &= rhs_set;
630                }
631                (RowIdSelection::Full, Some(RowIdSelection::Partial(rhs_set))) => {
632                    *lhs_set = RowIdSelection::Partial(rhs_set.clone());
633                }
634            }
635        }
636        // Some bitmaps might now be empty. If they are, we should remove them.
637        self.inner.retain(|_, set| match set {
638            RowIdSelection::Partial(set) => !set.is_empty(),
639            RowIdSelection::Full => true,
640        });
641    }
642}
643
644impl std::ops::SubAssign<&Self> for RowIdTreeMap {
645    fn sub_assign(&mut self, rhs: &Self) {
646        for (fragment, rhs_set) in &rhs.inner {
647            match self.inner.get_mut(fragment) {
648                None => {}
649                Some(RowIdSelection::Full) => {
650                    // If the fragment is already selected then there is nothing to do
651                    match rhs_set {
652                        RowIdSelection::Full => {
653                            self.inner.remove(fragment);
654                        }
655                        RowIdSelection::Partial(rhs_set) => {
656                            // This generally won't be hit.
657                            let mut set = RoaringBitmap::full();
658                            set -= rhs_set;
659                            self.inner.insert(*fragment, RowIdSelection::Partial(set));
660                        }
661                    }
662                }
663                Some(RowIdSelection::Partial(lhs_set)) => match rhs_set {
664                    RowIdSelection::Full => {
665                        self.inner.remove(fragment);
666                    }
667                    RowIdSelection::Partial(rhs_set) => {
668                        *lhs_set -= rhs_set;
669                        if lhs_set.is_empty() {
670                            self.inner.remove(fragment);
671                        }
672                    }
673                },
674            }
675        }
676    }
677}
678
679impl FromIterator<u64> for RowIdTreeMap {
680    fn from_iter<T: IntoIterator<Item = u64>>(iter: T) -> Self {
681        let mut inner = BTreeMap::new();
682        for row_id in iter {
683            let upper = (row_id >> 32) as u32;
684            let lower = row_id as u32;
685            match inner.get_mut(&upper) {
686                None => {
687                    let mut set = RoaringBitmap::new();
688                    set.insert(lower);
689                    inner.insert(upper, RowIdSelection::Partial(set));
690                }
691                Some(RowIdSelection::Full) => {
692                    // If the fragment is already selected then there is nothing to do
693                }
694                Some(RowIdSelection::Partial(set)) => {
695                    set.insert(lower);
696                }
697            }
698        }
699        Self { inner }
700    }
701}
702
703impl<'a> FromIterator<&'a u64> for RowIdTreeMap {
704    fn from_iter<T: IntoIterator<Item = &'a u64>>(iter: T) -> Self {
705        Self::from_iter(iter.into_iter().copied())
706    }
707}
708
709impl Extend<u64> for RowIdTreeMap {
710    fn extend<T: IntoIterator<Item = u64>>(&mut self, iter: T) {
711        for row_id in iter {
712            let upper = (row_id >> 32) as u32;
713            let lower = row_id as u32;
714            match self.inner.get_mut(&upper) {
715                None => {
716                    let mut set = RoaringBitmap::new();
717                    set.insert(lower);
718                    self.inner.insert(upper, RowIdSelection::Partial(set));
719                }
720                Some(RowIdSelection::Full) => {
721                    // If the fragment is already selected then there is nothing to do
722                }
723                Some(RowIdSelection::Partial(set)) => {
724                    set.insert(lower);
725                }
726            }
727        }
728    }
729}
730
731impl<'a> Extend<&'a u64> for RowIdTreeMap {
732    fn extend<T: IntoIterator<Item = &'a u64>>(&mut self, iter: T) {
733        self.extend(iter.into_iter().copied())
734    }
735}
736
737// Extending with RowIdTreeMap is basically a cumulative set union
738impl Extend<Self> for RowIdTreeMap {
739    fn extend<T: IntoIterator<Item = Self>>(&mut self, iter: T) {
740        for other in iter {
741            for (fragment, set) in other.inner {
742                match self.inner.get_mut(&fragment) {
743                    None => {
744                        self.inner.insert(fragment, set);
745                    }
746                    Some(RowIdSelection::Full) => {
747                        // If the fragment is already selected then there is nothing to do
748                    }
749                    Some(RowIdSelection::Partial(lhs_set)) => match set {
750                        RowIdSelection::Full => {
751                            self.inner.insert(fragment, RowIdSelection::Full);
752                        }
753                        RowIdSelection::Partial(rhs_set) => {
754                            *lhs_set |= rhs_set;
755                        }
756                    },
757                }
758            }
759        }
760    }
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766    use proptest::prop_assert_eq;
767
768    #[test]
769    fn test_ops() {
770        let mask = RowIdMask::default();
771        assert!(mask.selected(1));
772        assert!(mask.selected(5));
773        let block_list = mask.also_block(RowIdTreeMap::from_iter(&[0, 5, 15]));
774        assert!(block_list.selected(1));
775        assert!(!block_list.selected(5));
776        let allow_list = RowIdMask::from_allowed(RowIdTreeMap::from_iter(&[0, 2, 5]));
777        assert!(!allow_list.selected(1));
778        assert!(allow_list.selected(5));
779        let combined = block_list & allow_list;
780        assert!(combined.selected(2));
781        assert!(!combined.selected(0));
782        assert!(!combined.selected(5));
783        let other = RowIdMask::from_allowed(RowIdTreeMap::from_iter(&[3]));
784        let combined = combined | other;
785        assert!(combined.selected(2));
786        assert!(combined.selected(3));
787        assert!(!combined.selected(0));
788        assert!(!combined.selected(5));
789
790        let block_list = RowIdMask::from_block(RowIdTreeMap::from_iter(&[0]));
791        let allow_list = RowIdMask::from_allowed(RowIdTreeMap::from_iter(&[3]));
792        let combined = block_list | allow_list;
793        assert!(combined.selected(1));
794    }
795
796    #[test]
797    fn test_map_insert_range() {
798        let ranges = &[
799            (0..10),
800            (40..500),
801            ((u32::MAX as u64 - 10)..(u32::MAX as u64 + 20)),
802        ];
803
804        for range in ranges {
805            let mut mask = RowIdTreeMap::default();
806
807            let count = mask.insert_range(range.clone());
808            let expected = range.end - range.start;
809            assert_eq!(count, expected);
810
811            let count = mask.insert_range(range.clone());
812            assert_eq!(count, 0);
813
814            let new_range = range.start + 5..range.end + 5;
815            let count = mask.insert_range(new_range.clone());
816            assert_eq!(count, 5);
817        }
818
819        let mut mask = RowIdTreeMap::default();
820        let count = mask.insert_range(..10);
821        assert_eq!(count, 10);
822        assert!(mask.contains(0));
823
824        let count = mask.insert_range(20..=24);
825        assert_eq!(count, 5);
826
827        mask.insert_fragment(0);
828        let count = mask.insert_range(100..200);
829        assert_eq!(count, 0);
830    }
831
832    #[test]
833    fn test_map_remove() {
834        let mut mask = RowIdTreeMap::default();
835
836        assert!(!mask.remove(20));
837
838        mask.insert(20);
839        assert!(mask.contains(20));
840        assert!(mask.remove(20));
841        assert!(!mask.contains(20));
842
843        mask.insert_range(10..=20);
844        assert!(mask.contains(15));
845        assert!(mask.remove(15));
846        assert!(!mask.contains(15));
847
848        // We don't test removing from a full fragment, because that would take
849        // a lot of memory.
850    }
851
852    proptest::proptest! {
853        #[test]
854        fn test_map_serialization_roundtrip(
855            values in proptest::collection::vec(
856                (0..u32::MAX, proptest::option::of(proptest::collection::vec(0..u32::MAX, 0..1000))),
857                0..10
858            )
859        ) {
860            let mut mask = RowIdTreeMap::default();
861            for (fragment, rows) in values {
862                if let Some(rows) = rows {
863                    let bitmap = RoaringBitmap::from_iter(rows);
864                    mask.insert_bitmap(fragment, bitmap);
865                } else {
866                    mask.insert_fragment(fragment);
867                }
868            }
869
870            let mut data = Vec::new();
871            mask.serialize_into(&mut data).unwrap();
872            let deserialized = RowIdTreeMap::deserialize_from(data.as_slice()).unwrap();
873            prop_assert_eq!(mask, deserialized);
874        }
875
876        #[test]
877        fn test_map_intersect(
878            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
879            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
880            right_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
881            right_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
882        ) {
883            let mut left = RowIdTreeMap::default();
884            for fragment in left_full_fragments.clone() {
885                left.insert_fragment(fragment);
886            }
887            left.extend(left_rows.iter().copied());
888
889            let mut right = RowIdTreeMap::default();
890            for fragment in right_full_fragments.clone() {
891                right.insert_fragment(fragment);
892            }
893            right.extend(right_rows.iter().copied());
894
895            let mut expected = RowIdTreeMap::default();
896            for fragment in left_full_fragments {
897                if right_full_fragments.contains(&fragment) {
898                    expected.insert_fragment(fragment);
899                }
900            }
901
902            let combined_rows = left_rows.iter().filter(|row| right_rows.contains(row));
903            expected.extend(combined_rows);
904
905            let actual = left & right;
906            prop_assert_eq!(expected, actual);
907        }
908
909        #[test]
910        fn test_map_union(
911            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
912            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
913            right_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
914            right_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
915        ) {
916            let mut left = RowIdTreeMap::default();
917            for fragment in left_full_fragments.clone() {
918                left.insert_fragment(fragment);
919            }
920            left.extend(left_rows.iter().copied());
921
922            let mut right = RowIdTreeMap::default();
923            for fragment in right_full_fragments.clone() {
924                right.insert_fragment(fragment);
925            }
926            right.extend(right_rows.iter().copied());
927
928            let mut expected = RowIdTreeMap::default();
929            for fragment in left_full_fragments {
930                expected.insert_fragment(fragment);
931            }
932            for fragment in right_full_fragments {
933                expected.insert_fragment(fragment);
934            }
935
936            let combined_rows = left_rows.iter().chain(right_rows.iter());
937            expected.extend(combined_rows);
938
939            let actual = left | right;
940            prop_assert_eq!(expected, actual);
941        }
942
943        #[test]
944        fn test_map_subassign_rows(
945            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
946            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
947            right_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
948        ) {
949            let mut left = RowIdTreeMap::default();
950            for fragment in left_full_fragments {
951                left.insert_fragment(fragment);
952            }
953            left.extend(left_rows.iter().copied());
954
955            let mut right = RowIdTreeMap::default();
956            right.extend(right_rows.iter().copied());
957
958            let mut expected = left.clone();
959            for row in right_rows {
960                expected.remove(row);
961            }
962
963            left -= &right;
964            prop_assert_eq!(expected, left);
965        }
966
967        #[test]
968        fn test_map_subassign_frags(
969            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
970            right_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
971            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
972        ) {
973            let mut left = RowIdTreeMap::default();
974            for fragment in left_full_fragments {
975                left.insert_fragment(fragment);
976            }
977            left.extend(left_rows.iter().copied());
978
979            let mut right = RowIdTreeMap::default();
980            for fragment in right_full_fragments.clone() {
981                right.insert_fragment(fragment);
982            }
983
984            let mut expected = left.clone();
985            for fragment in right_full_fragments {
986                expected.inner.remove(&fragment);
987            }
988
989            left -= &right;
990            prop_assert_eq!(expected, left);
991        }
992    }
993}