Skip to main content

volas_core/
validity.rs

1//! Validity: an optional, packed missing-value mask for nullable column
2//! variants (`I64` / `I32` / `Bool`).
3//!
4//! `volas.NA` is one logical missing value, but each dtype stores it in its
5//! natural place: a float column uses `NaN` in-band (no mask), so only the
6//! integer and boolean variants carry a [`Validity`]. A [`Validity`] is `None`
7//! in the common dense case — every value present, **zero allocation** — and a
8//! packed [`Bitmap`] (1 bit per element, **set = present**) only once a missing
9//! value actually appears. This is the Arrow / pandas-nullable physical layout,
10//! kept behind a uniform `is_valid` interface so the rest of the library never
11//! sees the per-dtype storage difference.
12
13use std::sync::Arc;
14
15/// A packed validity mask: 1 bit per element, **set = present (valid)**, clear =
16/// missing (`volas.NA`). Bits are stored LSB-first in `u64` words; bits beyond
17/// `len` are kept clear so a popcount over every word counts exactly the present
18/// values.
19#[derive(Clone, Debug)]
20pub struct Bitmap {
21    words: Vec<u64>,
22    len: usize,
23}
24
25/// Words needed to hold `len` bits.
26fn words_for(len: usize) -> usize {
27    len.div_ceil(64)
28}
29
30impl Bitmap {
31    /// An all-present mask of `len` bits (every value valid).
32    pub fn all_valid(len: usize) -> Bitmap {
33        let mut words = vec![u64::MAX; words_for(len)];
34        // Clear the unused high bits of the final word so popcount == len.
35        if let Some(last) = words.last_mut() {
36            let used = len % 64;
37            if used != 0 {
38                *last = (1u64 << used) - 1;
39            }
40        }
41        Bitmap { words, len }
42    }
43
44    /// Build from an iterator of `valid` flags (true = present).
45    pub fn from_valid_iter(len: usize, valid: impl IntoIterator<Item = bool>) -> Bitmap {
46        let mut bm = Bitmap { words: vec![0; words_for(len)], len };
47        for (i, v) in valid.into_iter().enumerate().take(len) {
48            if v {
49                bm.words[i / 64] |= 1u64 << (i % 64);
50            }
51        }
52        bm
53    }
54
55    /// Number of elements.
56    pub fn len(&self) -> usize {
57        self.len
58    }
59
60    /// Whether the mask covers no elements.
61    pub fn is_empty(&self) -> bool {
62        self.len == 0
63    }
64
65    /// Whether element `i` is present (valid). `i` is assumed in bounds.
66    pub fn get(&self, i: usize) -> bool {
67        (self.words[i / 64] >> (i % 64)) & 1 == 1
68    }
69
70    /// Mark element `i` present (`valid = true`) or missing. `i` in bounds.
71    pub fn set(&mut self, i: usize, valid: bool) {
72        let (w, bit) = (i / 64, 1u64 << (i % 64));
73        if valid {
74            self.words[w] |= bit;
75        } else {
76            self.words[w] &= !bit;
77        }
78    }
79
80    /// Count of missing values (clear bits among the first `len`).
81    pub fn null_count(&self) -> usize {
82        let present: u32 = self.words.iter().map(|w| w.count_ones()).sum();
83        self.len - present as usize
84    }
85}
86
87impl PartialEq for Bitmap {
88    /// Equal when the same length and the same present/missing pattern (unused
89    /// high bits are always clear, so a plain word comparison is exact).
90    fn eq(&self, other: &Self) -> bool {
91        self.len == other.len && self.words == other.words
92    }
93}
94
95/// An optional validity mask. `None` (the dense default) means every value is
96/// present with no allocation; `Some` carries a [`Bitmap`] with at least one
97/// missing value. The invariant "`Some` ⇒ has a missing value" is upheld by the
98/// constructors so equality and `has_nulls` stay cheap and canonical.
99#[derive(Clone, Debug, Default)]
100pub struct Validity(Option<Arc<Bitmap>>);
101
102impl Validity {
103    /// A fully-present (dense) validity — no allocation.
104    pub fn dense() -> Validity {
105        Validity(None)
106    }
107
108    /// Wrap a bitmap, collapsing an all-present one back to dense so the dense
109    /// fast path is always taken when there are no missing values.
110    pub fn from_bitmap(bm: Bitmap) -> Validity {
111        if bm.null_count() == 0 {
112            Validity(None)
113        } else {
114            Validity(Some(Arc::new(bm)))
115        }
116    }
117
118    /// Build from an iterator of `valid` flags; dense when all are present.
119    pub fn from_valid_iter(len: usize, valid: impl IntoIterator<Item = bool>) -> Validity {
120        Validity::from_bitmap(Bitmap::from_valid_iter(len, valid))
121    }
122
123    /// Whether element `i` is present. Dense ⇒ always true. `i` in bounds.
124    pub fn is_valid(&self, i: usize) -> bool {
125        match &self.0 {
126            None => true,
127            Some(bm) => bm.get(i),
128        }
129    }
130
131    /// Set element `i`'s presence in place (one cell). Dense stays dense when
132    /// marking present; a bitmap is materialized only when a first missing value is
133    /// introduced. `len` is the column length, needed to size that fresh bitmap.
134    /// Backs the single-cell write in [`crate::Column::combine_at`].
135    pub fn set(&mut self, i: usize, len: usize, valid: bool) {
136        match &mut self.0 {
137            None => {
138                if !valid {
139                    let mut bm = Bitmap::all_valid(len);
140                    bm.set(i, false);
141                    self.0 = Some(Arc::new(bm));
142                }
143            }
144            Some(arc) => {
145                let bm = Arc::make_mut(arc);
146                // Only an actual 0->1 clear (filling the last hole) can empty the
147                // mask, so we re-collapse to dense ONLY then — preserving the
148                // "Some ⇒ has a missing value" invariant that `has_nulls` /
149                // `null_count` / `PartialEq` / the NA-aware export paths rely on.
150                // A no-op set-present or any set-missing skips the popcount, so the
151                // dense (`None`) hot path is untouched and the `Some` path pays the
152                // `null_count` scan only when a hole is genuinely filled.
153                let clearing_hole = valid && !bm.get(i);
154                bm.set(i, valid);
155                if clearing_hole && bm.null_count() == 0 {
156                    self.0 = None;
157                }
158            }
159        }
160    }
161
162    /// Whether any value is missing (cheap: dense ⇒ false).
163    pub fn has_nulls(&self) -> bool {
164        self.0.is_some()
165    }
166
167    /// Number of missing values (dense ⇒ 0).
168    pub fn null_count(&self) -> usize {
169        self.0.as_ref().map_or(0, |bm| bm.null_count())
170    }
171
172    /// Borrow the backing bitmap, if any (`None` when dense).
173    pub fn bitmap(&self) -> Option<&Bitmap> {
174        self.0.as_deref()
175    }
176
177    /// Combined validity of two equal-length columns: present only where **both**
178    /// are present — the missing-value rule for a binary op (`x ∘ NA = NA`).
179    pub fn and(&self, other: &Validity) -> Validity {
180        match (&self.0, &other.0) {
181            (None, None) => Validity::dense(),
182            // One side dense ⇒ the other's holes win (a `Some` already has a hole).
183            (Some(a), None) | (None, Some(a)) => Validity(Some(Arc::clone(a))),
184            (Some(a), Some(b)) => {
185                let n = a.len();
186                Validity::from_valid_iter(n, (0..n).map(|i| a.get(i) && b.get(i)))
187            }
188        }
189    }
190
191    /// Gather present-flags at `idx` (fancy indexing / dropna). Dense stays dense.
192    pub fn take(&self, idx: &[usize]) -> Validity {
193        match &self.0 {
194            None => Validity::dense(),
195            Some(bm) => Validity::from_valid_iter(idx.len(), idx.iter().map(|&i| bm.get(i))),
196        }
197    }
198
199    /// Present-flags over `[start, end)` (slicing). Dense stays dense.
200    pub fn slice(&self, start: usize, end: usize) -> Validity {
201        match &self.0 {
202            None => Validity::dense(),
203            Some(bm) => Validity::from_valid_iter(end - start, (start..end).map(|i| bm.get(i))),
204        }
205    }
206}
207
208impl PartialEq for Validity {
209    /// Dense compares equal to an all-present bitmap (the constructors keep
210    /// `Some` non-trivial, so in practice this reduces to comparing patterns).
211    fn eq(&self, other: &Self) -> bool {
212        match (&self.0, &other.0) {
213            (None, None) => true,
214            (Some(a), Some(b)) => a == b,
215            // Constructors collapse all-present to `None`, so a `Some` here has a
216            // missing value and can never equal a dense `None`.
217            (Some(_), None) | (None, Some(_)) => false,
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn validity_set_cell_in_place() {
228        let mut v = Validity::dense();
229        v.set(1, 3, true); // dense + still present -> stays dense (no allocation)
230        assert!(!v.has_nulls());
231        v.set(1, 3, false); // first missing value -> materialize a bitmap
232        assert!(v.has_nulls());
233        assert!(!v.is_valid(1) && v.is_valid(0));
234        v.set(1, 3, true); // Some(bitmap) branch -> back to present
235        assert!(v.is_valid(1));
236        // Clearing the LAST hole re-collapses to dense (C1): the `Some ⇒ has a
237        // missing value` invariant holds, so has_nulls/null_count stay canonical.
238        assert!(!v.has_nulls() && v.bitmap().is_none() && v.null_count() == 0);
239    }
240
241    #[test]
242    fn validity_set_collapses_only_on_last_hole() {
243        // Two holes: filling one stays Some (still a hole); filling the second
244        // re-collapses to dense. A no-op set-present must not collapse spuriously.
245        let mut v = Validity::from_valid_iter(4, [true, false, true, false]);
246        assert_eq!(v.null_count(), 2);
247        v.set(3, 4, true); // fill one hole -> still Some (idx 1 missing)
248        assert!(v.has_nulls() && v.null_count() == 1);
249        v.set(0, 4, true); // no-op set-present (already valid) -> stays Some
250        assert!(v.has_nulls() && v.null_count() == 1);
251        v.set(1, 4, true); // fill the last hole -> collapse to dense
252        assert!(!v.has_nulls() && v.bitmap().is_none());
253    }
254
255    #[test]
256    fn bitmap_get_set_and_null_count() {
257        let mut bm = Bitmap::all_valid(70); // spans two words
258        assert_eq!(bm.len(), 70);
259        assert!(!bm.is_empty());
260        assert_eq!(bm.null_count(), 0);
261        assert!(bm.get(0) && bm.get(69));
262        bm.set(3, false);
263        bm.set(64, false);
264        assert!(!bm.get(3) && !bm.get(64));
265        assert_eq!(bm.null_count(), 2);
266        bm.set(3, true);
267        assert!(bm.get(3));
268        assert_eq!(bm.null_count(), 1);
269    }
270
271    #[test]
272    fn bitmap_empty_and_full_word_boundary() {
273        assert!(Bitmap::all_valid(0).is_empty());
274        // exactly 64 bits: no partial-word masking, popcount == len
275        assert_eq!(Bitmap::all_valid(64).null_count(), 0);
276    }
277
278    #[test]
279    fn bitmap_from_valid_iter_and_eq() {
280        let a = Bitmap::from_valid_iter(3, [true, false, true]);
281        let b = Bitmap::from_valid_iter(3, [true, false, true]);
282        assert_eq!(a, b);
283        assert_eq!(a.null_count(), 1);
284        assert!(!a.get(1));
285        assert_ne!(a, Bitmap::from_valid_iter(3, [true, true, true]));
286        assert_ne!(a, Bitmap::from_valid_iter(2, [true, false])); // length differs
287    }
288
289    #[test]
290    fn validity_dense_is_all_valid() {
291        let v = Validity::dense();
292        assert!(!v.has_nulls());
293        assert_eq!(v.null_count(), 0);
294        assert!(v.is_valid(0) && v.is_valid(999));
295        assert!(v.bitmap().is_none());
296    }
297
298    #[test]
299    fn validity_collapses_all_present_to_dense() {
300        // an all-present bitmap becomes dense (None)
301        let v = Validity::from_valid_iter(3, [true, true, true]);
302        assert!(!v.has_nulls());
303        assert!(v.bitmap().is_none());
304        // a bitmap with a hole stays Some
305        let v = Validity::from_valid_iter(3, [true, false, true]);
306        assert!(v.has_nulls());
307        assert_eq!(v.null_count(), 1);
308        assert!(!v.is_valid(1) && v.is_valid(0));
309        assert!(v.bitmap().is_some());
310    }
311
312    #[test]
313    fn validity_from_bitmap_and_default() {
314        assert_eq!(Validity::default(), Validity::dense());
315        let v = Validity::from_bitmap(Bitmap::all_valid(4));
316        assert!(!v.has_nulls()); // collapsed to dense
317    }
318
319    #[test]
320    fn validity_eq() {
321        let dense = Validity::dense();
322        let holed = Validity::from_valid_iter(2, [true, false]);
323        assert_eq!(dense, Validity::dense());
324        assert_eq!(holed, Validity::from_valid_iter(2, [true, false]));
325        assert_ne!(dense, holed);
326        assert_ne!(holed, dense);
327        assert_ne!(holed, Validity::from_valid_iter(2, [false, true]));
328    }
329
330    #[test]
331    fn validity_and_combines_holes() {
332        let dense = Validity::dense();
333        let a = Validity::from_valid_iter(3, [true, false, true]);
334        let b = Validity::from_valid_iter(3, [true, true, false]);
335        assert_eq!(dense.and(&dense), Validity::dense()); // both dense
336        assert_eq!(dense.and(&a), a); // dense ∧ holed -> holed
337        assert_eq!(a.and(&dense), a); // holed ∧ dense -> holed
338        // hole from either side wins
339        assert_eq!(a.and(&b), Validity::from_valid_iter(3, [true, false, false]));
340    }
341}