Skip to main content

vortex_array/builders/
null.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5
6use vortex_error::VortexResult;
7use vortex_error::vortex_ensure;
8
9use crate::ArrayRef;
10use crate::ExecutionCtx;
11use crate::IntoArray;
12use crate::arrays::NullArray;
13use crate::builders::ArrayBuilder;
14use crate::canonical::Canonical;
15use crate::dtype::DType;
16use crate::scalar::Scalar;
17
18/// The builder for building a [`NullArray`].
19pub struct NullBuilder {
20    length: usize,
21}
22
23impl Default for NullBuilder {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl NullBuilder {
30    pub fn new() -> Self {
31        Self { length: 0 }
32    }
33}
34
35impl ArrayBuilder for NullBuilder {
36    fn as_any(&self) -> &dyn Any {
37        self
38    }
39
40    fn as_any_mut(&mut self) -> &mut dyn Any {
41        self
42    }
43
44    fn dtype(&self) -> &DType {
45        &DType::Null
46    }
47
48    fn len(&self) -> usize {
49        self.length
50    }
51
52    fn append_zeros(&mut self, n: usize) {
53        self.length += n;
54    }
55
56    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
57        self.length += n;
58    }
59
60    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
61        vortex_ensure!(
62            scalar.dtype() == self.dtype(),
63            "NullBuilder expected scalar with dtype {}, got {}",
64            self.dtype(),
65            scalar.dtype()
66        );
67
68        self.append_null();
69        Ok(())
70    }
71
72    fn reserve_exact(&mut self, _additional: usize) {}
73
74    fn finish(&mut self) -> ArrayRef {
75        NullArray::new(self.length).into_array()
76    }
77
78    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
79        Canonical::Null(NullArray::new(self.length))
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::builders::ArrayBuilder;
87    use crate::dtype::DType;
88    use crate::scalar::Scalar;
89
90    #[test]
91    fn test_append_scalar() {
92        let mut builder = NullBuilder::new();
93
94        // Test appending null scalar.
95        let null_scalar = Scalar::null(DType::Null);
96        builder.append_scalar(&null_scalar).unwrap();
97        builder.append_scalar(&null_scalar).unwrap();
98        builder.append_scalar(&null_scalar).unwrap();
99
100        let array = builder.finish();
101        assert_eq!(array.len(), 3);
102
103        // For null arrays, all values are null - nothing to check for actual values.
104        // Just verify the array is indeed a null array with the right length.
105
106        // Test wrong dtype error.
107        let mut builder = NullBuilder::new();
108        let wrong_scalar = Scalar::from(42i32);
109        assert!(builder.append_scalar(&wrong_scalar).is_err());
110    }
111}