Skip to main content

vortex_array/builders/
lazy_null_builder.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::BitBuffer;
5use vortex_buffer::BitBufferMut;
6use vortex_buffer::BufferAllocatorRef;
7use vortex_error::VortexExpect;
8use vortex_error::vortex_panic;
9use vortex_mask::Mask;
10
11use crate::dtype::Nullability;
12use crate::dtype::Nullability::NonNullable;
13use crate::dtype::Nullability::Nullable;
14use crate::validity::Validity;
15
16/// This is borrowed from arrow's null buffer builder, however we expose a `append_buffer`
17/// method to append a boolean buffer directly.
18pub struct LazyBitBufferBuilder {
19    inner: Option<BitBufferMut>,
20    len: usize,
21    capacity: usize,
22    allocator: BufferAllocatorRef,
23}
24
25impl LazyBitBufferBuilder {
26    /// Creates a new empty builder.
27    /// `capacity` is the number of bits in the null buffer.
28    pub fn new(capacity: usize, allocator: BufferAllocatorRef) -> Self {
29        Self {
30            inner: None,
31            len: 0,
32            capacity,
33            allocator,
34        }
35    }
36
37    /// Appends `n` non-null values to the builder.
38    #[inline]
39    pub fn append_n_non_nulls(&mut self, n: usize) {
40        if let Some(buf) = self.inner.as_mut() {
41            buf.append_n(true, n)
42        } else {
43            self.len += n;
44        }
45    }
46
47    /// Appends a single non-null value to the builder.
48    #[inline]
49    pub fn append_non_null(&mut self) {
50        if let Some(buf) = self.inner.as_mut() {
51            buf.append(true)
52        } else {
53            self.len += 1;
54        }
55    }
56
57    /// Appends `n` null values to the builder.
58    #[inline]
59    pub fn append_n_nulls(&mut self, n: usize) {
60        self.materialize_if_needed();
61        self.inner
62            .as_mut()
63            .vortex_expect("cannot append null to non-nullable builder")
64            .append_n(false, n);
65    }
66
67    /// Appends a single null value to the builder.
68    #[inline]
69    pub fn append_null(&mut self) {
70        self.materialize_if_needed();
71        self.inner
72            .as_mut()
73            .vortex_expect("cannot append null to non-nullable builder")
74            .append(false);
75    }
76
77    /// Appends values from a boolean buffer where `true` indicates non-null.
78    #[inline]
79    pub fn append_buffer(&mut self, bool_buffer: &BitBuffer) {
80        self.materialize_if_needed();
81        self.inner
82            .as_mut()
83            .vortex_expect("buffer just materialized")
84            .append_buffer(bool_buffer);
85    }
86
87    /// Appends values from a validity mask.
88    ///
89    /// Takes the mask by reference: the `Mask::Values` case copies the underlying buffer into the
90    /// running null buffer, so there is nothing to gain from owning the mask.
91    pub fn append_validity_mask(&mut self, validity_mask: &Mask) {
92        match validity_mask {
93            Mask::AllTrue(len) => self.append_n_non_nulls(*len),
94            Mask::AllFalse(len) => self.append_n_nulls(*len),
95            Mask::Values(is_valid) => self.append_buffer(is_valid.bit_buffer()),
96        }
97    }
98
99    /// Sets the validity bit at the given index.
100    pub fn set_bit(&mut self, index: usize, v: bool) {
101        self.materialize_if_needed();
102        self.inner
103            .as_mut()
104            .vortex_expect("buffer just materialized")
105            .set_to(index, v);
106    }
107
108    /// Returns the current length of the builder.
109    /// Whether no entries have been appended.
110    pub fn is_empty(&self) -> bool {
111        self.len() == 0
112    }
113
114    pub fn len(&self) -> usize {
115        // self.len is the length of the builder if the inner buffer is not materialized
116        self.inner.as_ref().map(|i| i.len()).unwrap_or(self.len)
117    }
118
119    /// The validity bits appended so far, or `None` when every entry is valid.
120    pub fn finish(&mut self) -> Option<BitBuffer> {
121        self.len = 0;
122        self.inner.take().map(|b| b.freeze())
123    }
124
125    /// Finishes the builder and returns a `Validity` based on the given nullability.
126    pub fn finish_with_nullability(&mut self, nullability: Nullability) -> Validity {
127        let nulls = self.finish();
128
129        match (nullability, nulls) {
130            (NonNullable, None) => Validity::NonNullable,
131            (Nullable, None) => Validity::AllValid,
132            (Nullable, Some(arr)) => Validity::from(arr),
133            _ => vortex_panic!("Invalid nullability/nulls combination"),
134        }
135    }
136
137    /// Ensures the builder can hold `additional` extra values.
138    pub fn reserve_exact(&mut self, additional: usize) {
139        if self.inner.is_none() {
140            self.capacity += additional;
141        } else {
142            self.inner
143                .as_mut()
144                .vortex_expect("buffer just materialized")
145                .reserve(additional);
146        }
147    }
148
149    fn materialize_if_needed(&mut self) {
150        if self.inner.is_none() {
151            self.materialize()
152        }
153    }
154
155    // This only happens once per builder
156    #[cold]
157    #[inline(never)]
158    fn materialize(&mut self) {
159        if self.inner.is_none() {
160            let mut bit_mut =
161                BitBufferMut::with_capacity_in(self.len.max(self.capacity), self.allocator.clone());
162            bit_mut.append_n(true, self.len);
163            self.inner = Some(bit_mut);
164        }
165    }
166}