Skip to main content

vortex_array/builders/
bool.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5
6use vortex_buffer::BitBufferMut;
7use vortex_buffer::BufferAllocatorRef;
8use vortex_error::VortexResult;
9use vortex_error::vortex_ensure_eq;
10
11use crate::ArrayRef;
12use crate::ExecutionCtx;
13use crate::IntoArray;
14use crate::array::ArrayView;
15use crate::arrays::Bool;
16use crate::arrays::BoolArray;
17use crate::arrays::bool::BoolArrayExt;
18use crate::builders::ArrayBuilder;
19use crate::builders::DEFAULT_BUILDER_CAPACITY;
20use crate::builders::LazyBitBufferBuilder;
21use crate::canonical::Canonical;
22use crate::dtype::DType;
23use crate::dtype::Nullability;
24use crate::scalar::Scalar;
25
26pub struct BoolBuilder {
27    dtype: DType,
28    inner: BitBufferMut,
29    nulls: LazyBitBufferBuilder,
30}
31
32impl BoolBuilder {
33    /// Creates a builder with the default capacity.
34    #[deprecated(note = "use `new_in` with an explicit allocator")]
35    pub fn new(nullability: Nullability) -> Self {
36        Self::new_in(nullability, BufferAllocatorRef::static_ref())
37    }
38
39    /// Creates a builder with the default capacity using `allocator`.
40    pub fn new_in(nullability: Nullability, allocator: &BufferAllocatorRef) -> Self {
41        Self::with_capacity_in(nullability, DEFAULT_BUILDER_CAPACITY, allocator)
42    }
43
44    /// Creates a builder with the given capacity.
45    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
46    pub fn with_capacity(nullability: Nullability, capacity: usize) -> Self {
47        Self::with_capacity_in(nullability, capacity, BufferAllocatorRef::static_ref())
48    }
49
50    /// Creates a builder with the given capacity and allocator.
51    pub fn with_capacity_in(
52        nullability: Nullability,
53        capacity: usize,
54        allocator: &BufferAllocatorRef,
55    ) -> Self {
56        Self {
57            inner: BitBufferMut::with_capacity_in(capacity, allocator.clone()),
58            nulls: LazyBitBufferBuilder::new(capacity, allocator.clone()),
59            dtype: DType::Bool(nullability),
60        }
61    }
62
63    /// Appends a boolean value to the builder.
64    pub fn append_value(&mut self, value: bool) {
65        self.append_values(value, 1)
66    }
67
68    /// Appends the same boolean value multiple times to the builder.
69    ///
70    /// This method appends the given boolean value `n` times.
71    pub fn append_values(&mut self, value: bool, n: usize) {
72        self.inner.append_n(value, n);
73        self.nulls.append_n_non_nulls(n)
74    }
75
76    /// Finishes the builder directly into a [`BoolArray`].
77    pub fn finish_into_bool(&mut self) -> BoolArray {
78        assert_eq!(
79            self.nulls.len(),
80            self.inner.len(),
81            "Null count and value count should match when calling BoolBuilder::finish."
82        );
83
84        // SAFETY: the assert above establishes the only invariant, that the validity covers
85        // exactly the bits appended.
86        unsafe {
87            BoolArray::new_unchecked(
88                self.inner.take().freeze(),
89                self.nulls.finish_with_nullability(self.dtype.nullability()),
90            )
91        }
92    }
93
94    pub(crate) fn append_bool_array(
95        &mut self,
96        array: ArrayView<'_, Bool>,
97        ctx: &mut ExecutionCtx,
98    ) -> VortexResult<()> {
99        self.inner.append_buffer(&array.to_bit_buffer());
100        self.nulls
101            .append_validity_mask(&BoolArrayExt::validity(&array).execute_mask(array.len(), ctx)?);
102        Ok(())
103    }
104}
105
106impl ArrayBuilder for BoolBuilder {
107    fn as_any(&self) -> &dyn Any {
108        self
109    }
110
111    fn as_any_mut(&mut self) -> &mut dyn Any {
112        self
113    }
114
115    fn dtype(&self) -> &DType {
116        &self.dtype
117    }
118
119    fn len(&self) -> usize {
120        self.inner.len()
121    }
122
123    fn append_zeros(&mut self, n: usize) {
124        self.append_values(false, n)
125    }
126
127    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
128        self.inner.append_n(false, n);
129        self.nulls.append_n_nulls(n)
130    }
131
132    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
133        vortex_ensure_eq!(
134            scalar.dtype(),
135            self.dtype(),
136            "BoolBuilder received a scalar with the wrong dtype"
137        );
138
139        match scalar.as_bool().value() {
140            Some(value) => self.append_value(value),
141            None => self.append_null(),
142        }
143
144        Ok(())
145    }
146
147    fn reserve_exact(&mut self, additional: usize) {
148        self.inner.reserve(additional);
149        self.nulls.reserve_exact(additional);
150    }
151
152    fn finish(&mut self) -> ArrayRef {
153        self.finish_into_bool().into_array()
154    }
155
156    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
157        Canonical::Bool(self.finish_into_bool())
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use std::sync::LazyLock;
164
165    use rand::RngExt;
166    use rand::SeedableRng;
167    use rand::prelude::StdRng;
168    use vortex_buffer::BufferAllocatorRef;
169    use vortex_error::VortexResult;
170    use vortex_session::VortexSession;
171
172    use crate::ArrayRef;
173    use crate::IntoArray;
174    use crate::VortexSessionExecute;
175    use crate::arrays::ChunkedArray;
176    use crate::arrays::bool::BoolArrayExt;
177    use crate::assert_arrays_eq;
178    use crate::builders::ArrayBuilder;
179    use crate::builders::BoolBuilder;
180    use crate::builders::bool::BoolArray;
181    use crate::builders::builder_with_capacity_in;
182    use crate::dtype::DType;
183    use crate::dtype::Nullability;
184    use crate::scalar::Scalar;
185
186    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
187
188    fn make_opt_bool_chunks(len: usize, chunk_count: usize) -> (ArrayRef, Vec<Option<bool>>) {
189        let mut rng = StdRng::seed_from_u64(0);
190
191        let mut expected = Vec::with_capacity(len * chunk_count);
192        let chunks = (0..chunk_count)
193            .map(|_| {
194                let values: Vec<_> = (0..len)
195                    .map(|_| match rng.random_range::<u8, _>(0..=2) {
196                        0 => Some(false),
197                        1 => Some(true),
198                        2 => None,
199                        _ => unreachable!(),
200                    })
201                    .collect();
202                expected.extend_from_slice(&values);
203                BoolArray::from_iter(values).into_array()
204            })
205            .collect::<ChunkedArray>()
206            .into_array();
207        (chunks, expected)
208    }
209
210    #[test]
211    fn tests() -> VortexResult<()> {
212        let len = 1000;
213        let chunk_count = 10;
214        let (chunk, expected) = make_opt_bool_chunks(len, chunk_count);
215
216        let mut ctx = SESSION.create_execution_ctx();
217        let mut builder = builder_with_capacity_in(
218            chunk.dtype(),
219            len * chunk_count,
220            BufferAllocatorRef::static_ref(),
221        );
222        chunk
223            .clone()
224            .append_to_builder(builder.as_mut(), &mut ctx)?;
225
226        let canon_into = builder.finish().execute::<BoolArray>(&mut ctx)?;
227        let into_canon = chunk.clone().execute::<BoolArray>(&mut ctx)?;
228
229        assert!(canon_into.validity()?.mask_eq(
230            &into_canon.validity()?,
231            canon_into.len(),
232            &mut ctx
233        )?);
234        assert_eq!(canon_into.to_bit_buffer(), into_canon.to_bit_buffer());
235        let expected = BoolArray::from_iter(expected);
236        assert_arrays_eq!(canon_into, &expected, &mut ctx);
237        assert_arrays_eq!(into_canon, expected, &mut ctx);
238        Ok(())
239    }
240
241    #[test]
242    fn test_append_scalar() {
243        let mut ctx = SESSION.create_execution_ctx();
244        let mut builder = BoolBuilder::with_capacity_in(
245            Nullability::Nullable,
246            10,
247            BufferAllocatorRef::static_ref(),
248        );
249
250        // Test appending true value.
251        let true_scalar = Scalar::bool(true, Nullability::Nullable);
252        builder.append_scalar(&true_scalar).unwrap();
253
254        // Test appending false value.
255        let false_scalar = Scalar::bool(false, Nullability::Nullable);
256        builder.append_scalar(&false_scalar).unwrap();
257
258        // Test appending null value.
259        let null_scalar = Scalar::null(DType::Bool(Nullability::Nullable));
260        builder.append_scalar(&null_scalar).unwrap();
261
262        let array = builder.finish_into_bool();
263        let expected = BoolArray::from_iter([Some(true), Some(false), None]);
264        assert_arrays_eq!(&array, &expected, &mut ctx);
265
266        // Test wrong dtype error.
267        let mut builder = BoolBuilder::with_capacity_in(
268            Nullability::NonNullable,
269            10,
270            BufferAllocatorRef::static_ref(),
271        );
272        let wrong_scalar = Scalar::from(42i32);
273        assert!(builder.append_scalar(&wrong_scalar).is_err());
274    }
275}