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, RoaringTreemap};
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    ///
522    /// If bitmap size is zero then the entire fragment is selected.
523    pub fn serialize_into<W: Write>(&self, mut writer: W) -> Result<()> {
524        writer.write_u32::<byteorder::LittleEndian>(self.inner.len() as u32)?;
525        for (fragment, set) in &self.inner {
526            writer.write_u32::<byteorder::LittleEndian>(*fragment)?;
527            if let RowIdSelection::Partial(set) = set {
528                writer.write_u32::<byteorder::LittleEndian>(set.serialized_size() as u32)?;
529                set.serialize_into(&mut writer)?;
530            } else {
531                writer.write_u32::<byteorder::LittleEndian>(0)?;
532            }
533        }
534        Ok(())
535    }
536
537    /// Deserialize the set from the given buffer
538    pub fn deserialize_from<R: Read>(mut reader: R) -> Result<Self> {
539        let num_entries = reader.read_u32::<byteorder::LittleEndian>()?;
540        let mut inner = BTreeMap::new();
541        for _ in 0..num_entries {
542            let fragment = reader.read_u32::<byteorder::LittleEndian>()?;
543            let bitmap_size = reader.read_u32::<byteorder::LittleEndian>()?;
544            if bitmap_size == 0 {
545                inner.insert(fragment, RowIdSelection::Full);
546            } else {
547                let mut buffer = vec![0; bitmap_size as usize];
548                reader.read_exact(&mut buffer)?;
549                let set = RoaringBitmap::deserialize_from(&buffer[..])?;
550                inner.insert(fragment, RowIdSelection::Partial(set));
551            }
552        }
553        Ok(Self { inner })
554    }
555
556    pub fn union_all(maps: &[&Self]) -> Self {
557        let mut new_map = BTreeMap::new();
558
559        for map in maps {
560            for (fragment, selection) in &map.inner {
561                new_map
562                    .entry(fragment)
563                    // I hate this allocation, but I can't think of a better way
564                    .or_insert_with(|| Vec::with_capacity(maps.len()))
565                    .push(selection);
566            }
567        }
568
569        let new_map = new_map
570            .into_iter()
571            .map(|(&fragment, selections)| (fragment, RowIdSelection::union_all(&selections)))
572            .collect();
573
574        Self { inner: new_map }
575    }
576}
577
578impl std::ops::BitOr<Self> for RowIdTreeMap {
579    type Output = Self;
580
581    fn bitor(mut self, rhs: Self) -> Self::Output {
582        self |= rhs;
583        self
584    }
585}
586
587impl std::ops::BitOrAssign<Self> for RowIdTreeMap {
588    fn bitor_assign(&mut self, rhs: Self) {
589        for (fragment, rhs_set) in &rhs.inner {
590            match self.inner.get_mut(fragment) {
591                None => {
592                    self.inner.insert(*fragment, rhs_set.clone());
593                }
594                Some(RowIdSelection::Full) => {
595                    // If the fragment is already selected then there is nothing to do
596                }
597                Some(RowIdSelection::Partial(lhs_set)) => {
598                    if let RowIdSelection::Partial(rhs_set) = rhs_set {
599                        *lhs_set |= rhs_set;
600                    }
601                }
602            }
603        }
604    }
605}
606
607impl std::ops::BitAnd<Self> for RowIdTreeMap {
608    type Output = Self;
609
610    fn bitand(mut self, rhs: Self) -> Self::Output {
611        self &= rhs;
612        self
613    }
614}
615
616impl std::ops::BitAndAssign<Self> for RowIdTreeMap {
617    fn bitand_assign(&mut self, rhs: Self) {
618        // Remove fragment that aren't on the RHS
619        self.inner
620            .retain(|fragment, _| rhs.inner.contains_key(fragment));
621
622        // For fragments that are on the RHS, intersect the bitmaps
623        for (fragment, mut lhs_set) in &mut self.inner {
624            match (&mut lhs_set, rhs.inner.get(fragment)) {
625                (_, None) => {} // Already handled by retain
626                (_, Some(RowIdSelection::Full)) => {
627                    // Everything selected on RHS, so can leave LHS untouched.
628                }
629                (RowIdSelection::Partial(lhs_set), Some(RowIdSelection::Partial(rhs_set))) => {
630                    *lhs_set &= rhs_set;
631                }
632                (RowIdSelection::Full, Some(RowIdSelection::Partial(rhs_set))) => {
633                    *lhs_set = RowIdSelection::Partial(rhs_set.clone());
634                }
635            }
636        }
637        // Some bitmaps might now be empty. If they are, we should remove them.
638        self.inner.retain(|_, set| match set {
639            RowIdSelection::Partial(set) => !set.is_empty(),
640            RowIdSelection::Full => true,
641        });
642    }
643}
644
645impl std::ops::SubAssign<&Self> for RowIdTreeMap {
646    fn sub_assign(&mut self, rhs: &Self) {
647        for (fragment, rhs_set) in &rhs.inner {
648            match self.inner.get_mut(fragment) {
649                None => {}
650                Some(RowIdSelection::Full) => {
651                    // If the fragment is already selected then there is nothing to do
652                    match rhs_set {
653                        RowIdSelection::Full => {
654                            self.inner.remove(fragment);
655                        }
656                        RowIdSelection::Partial(rhs_set) => {
657                            // This generally won't be hit.
658                            let mut set = RoaringBitmap::full();
659                            set -= rhs_set;
660                            self.inner.insert(*fragment, RowIdSelection::Partial(set));
661                        }
662                    }
663                }
664                Some(RowIdSelection::Partial(lhs_set)) => match rhs_set {
665                    RowIdSelection::Full => {
666                        self.inner.remove(fragment);
667                    }
668                    RowIdSelection::Partial(rhs_set) => {
669                        *lhs_set -= rhs_set;
670                        if lhs_set.is_empty() {
671                            self.inner.remove(fragment);
672                        }
673                    }
674                },
675            }
676        }
677    }
678}
679
680impl FromIterator<u64> for RowIdTreeMap {
681    fn from_iter<T: IntoIterator<Item = u64>>(iter: T) -> Self {
682        let mut inner = BTreeMap::new();
683        for row_id in iter {
684            let upper = (row_id >> 32) as u32;
685            let lower = row_id as u32;
686            match inner.get_mut(&upper) {
687                None => {
688                    let mut set = RoaringBitmap::new();
689                    set.insert(lower);
690                    inner.insert(upper, RowIdSelection::Partial(set));
691                }
692                Some(RowIdSelection::Full) => {
693                    // If the fragment is already selected then there is nothing to do
694                }
695                Some(RowIdSelection::Partial(set)) => {
696                    set.insert(lower);
697                }
698            }
699        }
700        Self { inner }
701    }
702}
703
704impl<'a> FromIterator<&'a u64> for RowIdTreeMap {
705    fn from_iter<T: IntoIterator<Item = &'a u64>>(iter: T) -> Self {
706        Self::from_iter(iter.into_iter().copied())
707    }
708}
709
710impl From<RoaringTreemap> for RowIdTreeMap {
711    fn from(roaring: RoaringTreemap) -> Self {
712        let mut inner = BTreeMap::new();
713        for (fragment, set) in roaring.bitmaps() {
714            inner.insert(fragment, RowIdSelection::Partial(set.clone()));
715        }
716        Self { inner }
717    }
718}
719
720impl Extend<u64> for RowIdTreeMap {
721    fn extend<T: IntoIterator<Item = u64>>(&mut self, iter: T) {
722        for row_id in iter {
723            let upper = (row_id >> 32) as u32;
724            let lower = row_id as u32;
725            match self.inner.get_mut(&upper) {
726                None => {
727                    let mut set = RoaringBitmap::new();
728                    set.insert(lower);
729                    self.inner.insert(upper, RowIdSelection::Partial(set));
730                }
731                Some(RowIdSelection::Full) => {
732                    // If the fragment is already selected then there is nothing to do
733                }
734                Some(RowIdSelection::Partial(set)) => {
735                    set.insert(lower);
736                }
737            }
738        }
739    }
740}
741
742impl<'a> Extend<&'a u64> for RowIdTreeMap {
743    fn extend<T: IntoIterator<Item = &'a u64>>(&mut self, iter: T) {
744        self.extend(iter.into_iter().copied())
745    }
746}
747
748// Extending with RowIdTreeMap is basically a cumulative set union
749impl Extend<Self> for RowIdTreeMap {
750    fn extend<T: IntoIterator<Item = Self>>(&mut self, iter: T) {
751        for other in iter {
752            for (fragment, set) in other.inner {
753                match self.inner.get_mut(&fragment) {
754                    None => {
755                        self.inner.insert(fragment, set);
756                    }
757                    Some(RowIdSelection::Full) => {
758                        // If the fragment is already selected then there is nothing to do
759                    }
760                    Some(RowIdSelection::Partial(lhs_set)) => match set {
761                        RowIdSelection::Full => {
762                            self.inner.insert(fragment, RowIdSelection::Full);
763                        }
764                        RowIdSelection::Partial(rhs_set) => {
765                            *lhs_set |= rhs_set;
766                        }
767                    },
768                }
769            }
770        }
771    }
772}
773
774#[cfg(test)]
775mod tests {
776    use super::*;
777    use proptest::prop_assert_eq;
778
779    #[test]
780    fn test_ops() {
781        let mask = RowIdMask::default();
782        assert!(mask.selected(1));
783        assert!(mask.selected(5));
784        let block_list = mask.also_block(RowIdTreeMap::from_iter(&[0, 5, 15]));
785        assert!(block_list.selected(1));
786        assert!(!block_list.selected(5));
787        let allow_list = RowIdMask::from_allowed(RowIdTreeMap::from_iter(&[0, 2, 5]));
788        assert!(!allow_list.selected(1));
789        assert!(allow_list.selected(5));
790        let combined = block_list & allow_list;
791        assert!(combined.selected(2));
792        assert!(!combined.selected(0));
793        assert!(!combined.selected(5));
794        let other = RowIdMask::from_allowed(RowIdTreeMap::from_iter(&[3]));
795        let combined = combined | other;
796        assert!(combined.selected(2));
797        assert!(combined.selected(3));
798        assert!(!combined.selected(0));
799        assert!(!combined.selected(5));
800
801        let block_list = RowIdMask::from_block(RowIdTreeMap::from_iter(&[0]));
802        let allow_list = RowIdMask::from_allowed(RowIdTreeMap::from_iter(&[3]));
803        let combined = block_list | allow_list;
804        assert!(combined.selected(1));
805    }
806
807    #[test]
808    fn test_map_insert_range() {
809        let ranges = &[
810            (0..10),
811            (40..500),
812            ((u32::MAX as u64 - 10)..(u32::MAX as u64 + 20)),
813        ];
814
815        for range in ranges {
816            let mut mask = RowIdTreeMap::default();
817
818            let count = mask.insert_range(range.clone());
819            let expected = range.end - range.start;
820            assert_eq!(count, expected);
821
822            let count = mask.insert_range(range.clone());
823            assert_eq!(count, 0);
824
825            let new_range = range.start + 5..range.end + 5;
826            let count = mask.insert_range(new_range.clone());
827            assert_eq!(count, 5);
828        }
829
830        let mut mask = RowIdTreeMap::default();
831        let count = mask.insert_range(..10);
832        assert_eq!(count, 10);
833        assert!(mask.contains(0));
834
835        let count = mask.insert_range(20..=24);
836        assert_eq!(count, 5);
837
838        mask.insert_fragment(0);
839        let count = mask.insert_range(100..200);
840        assert_eq!(count, 0);
841    }
842
843    #[test]
844    fn test_map_remove() {
845        let mut mask = RowIdTreeMap::default();
846
847        assert!(!mask.remove(20));
848
849        mask.insert(20);
850        assert!(mask.contains(20));
851        assert!(mask.remove(20));
852        assert!(!mask.contains(20));
853
854        mask.insert_range(10..=20);
855        assert!(mask.contains(15));
856        assert!(mask.remove(15));
857        assert!(!mask.contains(15));
858
859        // We don't test removing from a full fragment, because that would take
860        // a lot of memory.
861    }
862
863    proptest::proptest! {
864        #[test]
865        fn test_map_serialization_roundtrip(
866            values in proptest::collection::vec(
867                (0..u32::MAX, proptest::option::of(proptest::collection::vec(0..u32::MAX, 0..1000))),
868                0..10
869            )
870        ) {
871            let mut mask = RowIdTreeMap::default();
872            for (fragment, rows) in values {
873                if let Some(rows) = rows {
874                    let bitmap = RoaringBitmap::from_iter(rows);
875                    mask.insert_bitmap(fragment, bitmap);
876                } else {
877                    mask.insert_fragment(fragment);
878                }
879            }
880
881            let mut data = Vec::new();
882            mask.serialize_into(&mut data).unwrap();
883            let deserialized = RowIdTreeMap::deserialize_from(data.as_slice()).unwrap();
884            prop_assert_eq!(mask, deserialized);
885        }
886
887        #[test]
888        fn test_map_intersect(
889            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
890            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
891            right_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
892            right_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
893        ) {
894            let mut left = RowIdTreeMap::default();
895            for fragment in left_full_fragments.clone() {
896                left.insert_fragment(fragment);
897            }
898            left.extend(left_rows.iter().copied());
899
900            let mut right = RowIdTreeMap::default();
901            for fragment in right_full_fragments.clone() {
902                right.insert_fragment(fragment);
903            }
904            right.extend(right_rows.iter().copied());
905
906            let mut expected = RowIdTreeMap::default();
907            for fragment in left_full_fragments {
908                if right_full_fragments.contains(&fragment) {
909                    expected.insert_fragment(fragment);
910                }
911            }
912
913            let combined_rows = left_rows.iter().filter(|row| right_rows.contains(row));
914            expected.extend(combined_rows);
915
916            let actual = left & right;
917            prop_assert_eq!(expected, actual);
918        }
919
920        #[test]
921        fn test_map_union(
922            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
923            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
924            right_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
925            right_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
926        ) {
927            let mut left = RowIdTreeMap::default();
928            for fragment in left_full_fragments.clone() {
929                left.insert_fragment(fragment);
930            }
931            left.extend(left_rows.iter().copied());
932
933            let mut right = RowIdTreeMap::default();
934            for fragment in right_full_fragments.clone() {
935                right.insert_fragment(fragment);
936            }
937            right.extend(right_rows.iter().copied());
938
939            let mut expected = RowIdTreeMap::default();
940            for fragment in left_full_fragments {
941                expected.insert_fragment(fragment);
942            }
943            for fragment in right_full_fragments {
944                expected.insert_fragment(fragment);
945            }
946
947            let combined_rows = left_rows.iter().chain(right_rows.iter());
948            expected.extend(combined_rows);
949
950            let actual = left | right;
951            prop_assert_eq!(expected, actual);
952        }
953
954        #[test]
955        fn test_map_subassign_rows(
956            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
957            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
958            right_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
959        ) {
960            let mut left = RowIdTreeMap::default();
961            for fragment in left_full_fragments {
962                left.insert_fragment(fragment);
963            }
964            left.extend(left_rows.iter().copied());
965
966            let mut right = RowIdTreeMap::default();
967            right.extend(right_rows.iter().copied());
968
969            let mut expected = left.clone();
970            for row in right_rows {
971                expected.remove(row);
972            }
973
974            left -= &right;
975            prop_assert_eq!(expected, left);
976        }
977
978        #[test]
979        fn test_map_subassign_frags(
980            left_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
981            right_full_fragments in proptest::collection::vec(0..u32::MAX, 0..10),
982            left_rows in proptest::collection::vec(0..u64::MAX, 0..1000),
983        ) {
984            let mut left = RowIdTreeMap::default();
985            for fragment in left_full_fragments {
986                left.insert_fragment(fragment);
987            }
988            left.extend(left_rows.iter().copied());
989
990            let mut right = RowIdTreeMap::default();
991            for fragment in right_full_fragments.clone() {
992                right.insert_fragment(fragment);
993            }
994
995            let mut expected = left.clone();
996            for fragment in right_full_fragments {
997                expected.inner.remove(&fragment);
998            }
999
1000            left -= &right;
1001            prop_assert_eq!(expected, left);
1002        }
1003    }
1004}