Skip to main content

arrow_buffer/buffer/
null.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::bit_iterator::{BitIndexIterator, BitIterator, BitSliceIterator};
6use crate::bit_util;
7use crate::buffer::BooleanBuffer;
8use crate::{Buffer, MutableBuffer, OverflowError};
9
10/// A [`BooleanBuffer`] used to encode validity (null values) for Arrow arrays
11///
12/// In the [Arrow specification], array validity is encoded in a packed bitmask with a
13/// `true` value indicating the corresponding slot is not null, and `false` indicating
14/// that it is null.
15///
16/// # See also
17/// * [`NullBufferBuilder`] for creating `NullBuffer`s
18///
19/// [Arrow specification]: https://arrow.apache.org/docs/format/Columnar.html#validity-bitmaps
20/// [`NullBufferBuilder`]: crate::NullBufferBuilder
21#[derive(Debug, Clone, Eq, PartialEq)]
22pub struct NullBuffer {
23    buffer: BooleanBuffer,
24    null_count: usize,
25}
26
27impl NullBuffer {
28    /// Create a new [`NullBuffer`] computing the null count
29    pub fn new(buffer: BooleanBuffer) -> Self {
30        let null_count = buffer.len() - buffer.count_set_bits();
31        Self { buffer, null_count }
32    }
33
34    /// Create a new [`NullBuffer`] of length `len` where all values are null
35    pub fn new_null(len: usize) -> Self {
36        Self {
37            buffer: BooleanBuffer::new_unset(len),
38            null_count: len,
39        }
40    }
41
42    /// Create a new [`NullBuffer`] of length `len` where all values are valid
43    ///
44    /// Note: it is more efficient to not set the null buffer if it is known to
45    /// be all valid (aka all values are not null)
46    pub fn new_valid(len: usize) -> Self {
47        Self {
48            buffer: BooleanBuffer::new_set(len),
49            null_count: 0,
50        }
51    }
52
53    /// Create a new [`NullBuffer`] with the provided `buffer` and `null_count`
54    ///
55    /// # Safety
56    ///
57    /// `buffer` must contain `null_count` `0` bits
58    pub unsafe fn new_unchecked(buffer: BooleanBuffer, null_count: usize) -> Self {
59        if cfg!(feature = "force_validate") {
60            let expected = buffer.len() - buffer.count_set_bits();
61            assert_eq!(null_count, expected, "null_count does not match buffer");
62        }
63        Self { buffer, null_count }
64    }
65
66    /// Computes the union of the nulls in two optional [`NullBuffer`]
67    ///
68    /// This is commonly used by binary operations where the result is NULL if either
69    /// of the input values is NULL. Handling the null mask separately in this way
70    /// can yield significant performance improvements over an iterator approach
71    pub fn union(lhs: Option<&NullBuffer>, rhs: Option<&NullBuffer>) -> Option<NullBuffer> {
72        match (lhs, rhs) {
73            (Some(lhs), Some(rhs)) if lhs.null_count() > 0 || rhs.null_count() > 0 => {
74                Some(Self::new(lhs.inner() & rhs.inner()))
75            }
76            (Some(n), None) | (None, Some(n)) if n.null_count() > 0 => Some(n.clone()),
77            (_, _) => None,
78        }
79    }
80
81    /// Computes the union of the nulls in multiple optional [`NullBuffer`]s
82    ///
83    /// See [`union`](Self::union)
84    pub fn union_many<'a>(
85        nulls: impl IntoIterator<Item = Option<&'a NullBuffer>>,
86    ) -> Option<NullBuffer> {
87        // Unwrap to BooleanBuffer because BitAndAssign is not implemented for NullBuffer
88        let mut buffers = nulls.into_iter().filter_map(|nb| match nb {
89            Some(nb) if nb.null_count > 0 => Some(nb.inner()),
90            _ => None,
91        });
92        let first = buffers.next()?;
93        let mut result = first.clone();
94        for buf in buffers {
95            result &= buf;
96        }
97        Some(Self::new(result))
98    }
99
100    /// Returns true if all nulls in `other` also exist in self
101    pub fn contains(&self, other: &NullBuffer) -> bool {
102        if other.null_count == 0 {
103            return true;
104        }
105        let lhs = self.inner().bit_chunks().iter_padded();
106        let rhs = other.inner().bit_chunks().iter_padded();
107        lhs.zip(rhs).all(|(l, r)| (l & !r) == 0)
108    }
109
110    /// Returns a new [`NullBuffer`] where each bit in the current null buffer
111    /// is repeated `count` times. This is useful for masking the nulls of
112    /// the child of a FixedSizeListArray based on its parent
113    ///
114    /// # Panics
115    ///
116    /// Panics if `self.len() * count` overflows `usize` or if the required
117    /// buffer cannot be allocated.
118    /// Use [`Self::try_expand`] for a fallible version.
119    pub fn expand(&self, count: usize) -> Self {
120        self.try_expand(count).unwrap_or_else(|err| panic!("{err}"))
121    }
122
123    /// Returns a new [`NullBuffer`] where each bit in the current null buffer
124    /// is repeated `count` times. This is useful for masking the nulls of
125    /// the child of a FixedSizeListArray based on its parent
126    ///
127    /// # Errors
128    ///
129    /// Errors if `self.len() * count` overflows `usize` or if the required
130    /// buffer cannot be allocated.
131    pub fn try_expand(&self, count: usize) -> Result<Self, OverflowError> {
132        let capacity = self
133            .buffer
134            .len()
135            .checked_mul(count)
136            .ok_or_else(|| OverflowError::new::<usize>("buffer length"))?;
137        let mut buffer = MutableBuffer::try_from_len_zeroed(bit_util::ceil(capacity, 8))
138            .map_err(|_| OverflowError::new::<usize>("buffer length"))?;
139
140        if count.is_multiple_of(8) {
141            // When count is a multiple of 8 every expanded run starts on a byte
142            // boundary (bit i starts at bit i*count, which is divisible by 8),
143            // so we can fill count/8 bytes of 0xFF at a time instead of setting
144            // bits individually.
145            let bytes_per_bit = count / 8;
146            let buf = buffer.as_mut();
147            for (start, end) in BitSliceIterator::new(
148                self.buffer.values(),
149                self.buffer.offset(),
150                self.buffer.len(),
151            ) {
152                let byte_start = start * bytes_per_bit;
153                let byte_end = end * bytes_per_bit;
154                buf[byte_start..byte_end].fill(0xFF);
155            }
156        } else if count.is_multiple_of(4) {
157            // count is a multiple of 4 but not 8: each bit's range starts and ends
158            // on a nibble boundary. Fill any full bytes, then OR in the partial nibble
159            // (0x0F if the range ends mid-byte, 0xF0 if it starts mid-byte).
160            let buf = buffer.as_mut();
161            for i in 0..self.buffer.len() {
162                if self.is_null(i) {
163                    continue;
164                }
165                let start_bit = i * count;
166                let end_bit = start_bit + count;
167                if start_bit.is_multiple_of(8) {
168                    buf[start_bit / 8..end_bit / 8].fill(0xFF);
169                    buf[end_bit / 8] |= 0x0F;
170                } else {
171                    buf[start_bit / 8] |= 0xF0;
172                    buf[start_bit / 8 + 1..end_bit / 8].fill(0xFF);
173                }
174            }
175        } else {
176            // For each contiguous run of valid bits [start, end), the corresponding
177            // output bits [start*count, end*count) are set. Boundary bytes that are
178            // only partially covered are ORed with a mask; fully covered interior
179            // bytes are filled with 0xFF.
180            let buf = buffer.as_mut();
181            for (start, end) in BitSliceIterator::new(
182                self.buffer.values(),
183                self.buffer.offset(),
184                self.buffer.len(),
185            ) {
186                let start_bit = start * count;
187                let end_bit = end * count;
188                let start_byte = start_bit / 8;
189                let start_offset = (start_bit % 8) as u32; // first bit to set within start_byte
190                let end_byte = end_bit / 8;
191                let end_offset = (end_bit % 8) as u32; // one-past-last bit within end_byte
192
193                if start_byte == end_byte {
194                    // All bits land in one byte: mask from start_offset up to end_offset.
195                    // 0xFF << start_offset  → bits [start_offset, 7] set
196                    // (1 << end_offset) - 1 → bits [0, end_offset) set
197                    // AND of both           → bits [start_offset, end_offset) set
198                    buf[start_byte] |= (0xFFu8 << start_offset) & ((1u8 << end_offset) - 1);
199                } else {
200                    if start_offset != 0 {
201                        // Partial leading byte: set bits from start_offset to bit 7.
202                        buf[start_byte] |= 0xFFu8 << start_offset;
203                    }
204                    // Full interior bytes (skip start_byte if it was only partially covered).
205                    let full_start = start_byte + (start_offset != 0) as usize;
206                    buf[full_start..end_byte].fill(0xFF);
207                    if end_offset != 0 {
208                        // Partial trailing byte: set bits 0 up to end_offset.
209                        // (1 << end_offset) - 1 → bits [0, end_offset) set
210                        buf[end_byte] |= (1u8 << end_offset) - 1;
211                    }
212                }
213            }
214        }
215        Ok(Self {
216            buffer: BooleanBuffer::new(buffer.into(), 0, capacity),
217            null_count: self.null_count * count,
218        })
219    }
220
221    /// Returns the length of this [`NullBuffer`] in bits
222    #[inline]
223    pub fn len(&self) -> usize {
224        self.buffer.len()
225    }
226
227    /// Returns the offset of this [`NullBuffer`] in bits
228    #[inline]
229    pub fn offset(&self) -> usize {
230        self.buffer.offset()
231    }
232
233    /// Returns true if this [`NullBuffer`] is empty
234    #[inline]
235    pub fn is_empty(&self) -> bool {
236        self.buffer.is_empty()
237    }
238
239    /// Free up unused memory.
240    pub fn shrink_to_fit(&mut self) {
241        self.buffer.shrink_to_fit();
242    }
243
244    /// Returns the null count for this [`NullBuffer`]
245    #[inline]
246    pub fn null_count(&self) -> usize {
247        self.null_count
248    }
249
250    /// Returns `true` if the value at `idx` is not null
251    ///
252    /// # Panics
253    ///
254    /// Panics if `idx >= self.len()`
255    #[inline]
256    pub fn is_valid(&self, idx: usize) -> bool {
257        self.buffer.value(idx)
258    }
259
260    /// Returns `true` if the value at `idx` is null
261    ///
262    /// # Panics
263    ///
264    /// Panics if `idx >= self.len()`
265    #[inline]
266    pub fn is_null(&self, idx: usize) -> bool {
267        !self.is_valid(idx)
268    }
269
270    /// Returns the packed validity of this [`NullBuffer`] not including any offset
271    #[inline]
272    pub fn validity(&self) -> &[u8] {
273        self.buffer.values()
274    }
275
276    /// Slices this [`NullBuffer`] by the provided `offset` and `length`
277    ///
278    /// # Panics
279    ///
280    /// Panics if `offset + len > self.len()`
281    pub fn slice(&self, offset: usize, len: usize) -> Self {
282        Self::new(self.buffer.slice(offset, len))
283    }
284
285    /// Returns an iterator over the bits in this [`NullBuffer`]
286    ///
287    /// * `true` indicates that the corresponding value is not NULL
288    /// * `false` indicates that the corresponding value is NULL
289    ///
290    /// Note: [`Self::valid_indices`] will be significantly faster for most use-cases
291    pub fn iter(&self) -> BitIterator<'_> {
292        self.buffer.iter()
293    }
294
295    /// Returns a [`BitIndexIterator`] over the valid indices in this [`NullBuffer`]
296    ///
297    /// Valid indices indicate the corresponding value is not NULL
298    pub fn valid_indices(&self) -> BitIndexIterator<'_> {
299        self.buffer.set_indices()
300    }
301
302    /// Returns a [`BitSliceIterator`] yielding contiguous ranges of valid indices
303    ///
304    /// Valid indices indicate the corresponding value is not NULL
305    pub fn valid_slices(&self) -> BitSliceIterator<'_> {
306        self.buffer.set_slices()
307    }
308
309    /// Calls the provided closure for each index in this null mask that is set
310    #[inline]
311    pub fn try_for_each_valid_idx<E, F: FnMut(usize) -> Result<(), E>>(
312        &self,
313        f: F,
314    ) -> Result<(), E> {
315        if self.null_count == self.len() {
316            return Ok(());
317        }
318        self.valid_indices().try_for_each(f)
319    }
320
321    /// Returns the inner [`BooleanBuffer`]
322    #[inline]
323    pub fn inner(&self) -> &BooleanBuffer {
324        &self.buffer
325    }
326
327    /// Returns the inner [`BooleanBuffer`]
328    #[inline]
329    pub fn into_inner(self) -> BooleanBuffer {
330        self.buffer
331    }
332
333    /// Returns the underlying [`Buffer`]
334    #[inline]
335    pub fn buffer(&self) -> &Buffer {
336        self.buffer.inner()
337    }
338
339    /// Create a [`NullBuffer`] from an *unsliced* validity bitmap (`offset = 0` **bits**) of length `len`.
340    ///
341    /// Returns `None` if there are no nulls (all values valid).
342    pub fn from_unsliced_buffer(buffer: impl Into<Buffer>, len: usize) -> Option<Self> {
343        let bb = BooleanBuffer::new(buffer.into(), 0, len);
344        let nb = NullBuffer::new(bb);
345        (nb.null_count() > 0).then_some(nb)
346    }
347
348    /// Claim memory used by this null buffer in the provided memory pool.
349    #[cfg(feature = "pool")]
350    pub fn claim(&self, pool: &dyn crate::MemoryPool) {
351        // NullBuffer wraps a BooleanBuffer which wraps a Buffer
352        self.buffer.inner().claim(pool);
353    }
354}
355
356impl<'a> IntoIterator for &'a NullBuffer {
357    type Item = bool;
358    type IntoIter = BitIterator<'a>;
359
360    fn into_iter(self) -> Self::IntoIter {
361        self.buffer.iter()
362    }
363}
364
365impl From<BooleanBuffer> for NullBuffer {
366    fn from(value: BooleanBuffer) -> Self {
367        Self::new(value)
368    }
369}
370
371impl From<&[bool]> for NullBuffer {
372    fn from(value: &[bool]) -> Self {
373        BooleanBuffer::from(value).into()
374    }
375}
376
377impl<const N: usize> From<&[bool; N]> for NullBuffer {
378    fn from(value: &[bool; N]) -> Self {
379        value[..].into()
380    }
381}
382
383impl From<Vec<bool>> for NullBuffer {
384    fn from(value: Vec<bool>) -> Self {
385        BooleanBuffer::from(value).into()
386    }
387}
388
389impl FromIterator<bool> for NullBuffer {
390    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
391        BooleanBuffer::from_iter(iter).into()
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn test_size() {
401        // This tests that the niche optimisation eliminates the overhead of an option
402        assert_eq!(
403            std::mem::size_of::<NullBuffer>(),
404            std::mem::size_of::<Option<NullBuffer>>()
405        );
406    }
407
408    #[test]
409    fn test_from_unsliced_buffer_with_nulls() {
410        // 0b10110010 → null(0), valid(1), null(2), null(3), valid(4), valid(5), null(6), valid(7)
411        let buf = Buffer::from([0b10110010u8]);
412        let result = NullBuffer::from_unsliced_buffer(buf, 8);
413        assert!(result.is_some());
414        let nb = result.unwrap();
415        assert_eq!(nb.len(), 8);
416        assert_eq!(nb.null_count(), 4);
417        assert!(nb.is_null(0));
418        assert!(nb.is_valid(1));
419        assert!(nb.is_null(2));
420        assert!(nb.is_null(3));
421        assert!(nb.is_valid(4));
422        assert!(nb.is_valid(5));
423        assert!(nb.is_null(6));
424        assert!(nb.is_valid(7));
425    }
426
427    #[test]
428    fn test_from_unsliced_buffer_all_valid() {
429        // All bits set = all valid, no nulls
430        let buf = Buffer::from([0b11111111u8]);
431        let result = NullBuffer::from_unsliced_buffer(buf, 8);
432        assert!(result.is_none());
433    }
434
435    #[test]
436    fn test_from_unsliced_buffer_all_null() {
437        // No bits set = all null
438        let buf = Buffer::from([0b00000000u8]);
439        let result = NullBuffer::from_unsliced_buffer(buf, 8);
440        assert!(result.is_some());
441        let nb = result.unwrap();
442        assert_eq!(nb.len(), 8);
443        assert_eq!(nb.null_count(), 8);
444    }
445
446    #[test]
447    fn test_from_unsliced_buffer_empty() {
448        let buf = Buffer::from([]);
449        let result = NullBuffer::from_unsliced_buffer(buf, 0);
450        assert!(result.is_none());
451    }
452
453    #[test]
454    fn test_union_many_all_none() {
455        let result = NullBuffer::union_many([None, None, None]);
456        assert!(result.is_none());
457    }
458
459    #[test]
460    fn test_union_many_single_some() {
461        let a = NullBuffer::from(&[true, false, true, true]);
462        let result = NullBuffer::union_many([Some(&a)]);
463        assert_eq!(result, Some(a));
464    }
465
466    #[test]
467    fn test_union_many_two_inputs() {
468        let a = NullBuffer::from(&[true, false, true, true]);
469        let b = NullBuffer::from(&[true, true, false, true]);
470        let result = NullBuffer::union_many([Some(&a), Some(&b)]);
471        let expected = NullBuffer::union(Some(&a), Some(&b));
472        assert_eq!(result, expected);
473    }
474
475    #[test]
476    fn test_union_many_three_inputs() {
477        let a = NullBuffer::from(&[true, false, true, true]);
478        let b = NullBuffer::from(&[true, true, false, true]);
479        let c = NullBuffer::from(&[false, true, true, true]);
480        let result = NullBuffer::union_many([Some(&a), Some(&b), Some(&c)]);
481        let expected = NullBuffer::from(&[false, false, false, true]);
482        assert_eq!(result, Some(expected));
483    }
484
485    #[test]
486    fn test_union_many_mixed_none() {
487        let a = NullBuffer::from(&[true, false, true, true]);
488        let b = NullBuffer::from(&[false, true, true, true]);
489        let result = NullBuffer::union_many([Some(&a), None, Some(&b)]);
490        let expected = NullBuffer::union(Some(&a), Some(&b));
491        assert_eq!(result, expected);
492    }
493
494    #[test]
495    fn test_union_many_empty_slice() {
496        let result = NullBuffer::union_many([] as [Option<&NullBuffer>; 0]);
497        assert!(result.is_none());
498    }
499
500    #[test]
501    fn test_union_many_no_nulls() {
502        let a = NullBuffer::from(&[true, true, true, true]);
503
504        let result = NullBuffer::union_many([Some(&a), Some(&a), Some(&a)]);
505        assert_eq!(result, None);
506    }
507
508    #[test]
509    fn test_union_no_nulls() {
510        let a = NullBuffer::from(&[true, true, true, true]);
511
512        let result = NullBuffer::union(Some(&a), Some(&a));
513        assert_eq!(result, None);
514
515        let result = NullBuffer::union(Some(&a), None);
516        assert_eq!(result, None);
517
518        let result = NullBuffer::union(None, Some(&a));
519        assert_eq!(result, None);
520    }
521
522    #[test]
523    fn test_union_nulls_one_side() {
524        let all_valid = NullBuffer::from(&[true, true, true, true]);
525        let all_null = NullBuffer::from(&[false, false, false, false]);
526
527        let result = NullBuffer::union(Some(&all_valid), Some(&all_null));
528        assert_eq!(result, Some(all_null.clone()));
529
530        let result = NullBuffer::union(Some(&all_null), Some(&all_valid));
531        assert_eq!(result, Some(all_null.clone()));
532    }
533
534    #[test]
535    fn test_expand_code_paths() {
536        let source = NullBuffer::from(&[true, false, true] as &[bool]);
537
538        for count in [8, 4, 3] {
539            let expanded = source.expand(count);
540            assert_eq!(expanded.len(), 3 * count);
541            assert_eq!(expanded.null_count(), count);
542            assert!((0..count).all(|i| expanded.is_valid(i)));
543            assert!((count..2 * count).all(|i| expanded.is_null(i)));
544            assert!((2 * count..3 * count).all(|i| expanded.is_valid(i)));
545        }
546    }
547
548    #[test]
549    #[should_panic(expected = "null_count does not match buffer")]
550    #[cfg(feature = "force_validate")]
551    fn new_unchecked_wrong_null_count_force_validate() {
552        let buffer = BooleanBuffer::from(vec![true, false, true]);
553        unsafe { NullBuffer::new_unchecked(buffer, 0) };
554    }
555}