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_eq;
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_eq!(
62            scalar.dtype(),
63            self.dtype(),
64            "NullBuilder received a scalar with the wrong dtype"
65        );
66
67        self.append_null();
68        Ok(())
69    }
70
71    fn reserve_exact(&mut self, _additional: usize) {}
72
73    fn finish(&mut self) -> ArrayRef {
74        NullArray::new(self.length).into_array()
75    }
76
77    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
78        Canonical::Null(NullArray::new(self.length))
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use crate::builders::ArrayBuilder;
86    use crate::dtype::DType;
87    use crate::scalar::Scalar;
88
89    #[test]
90    fn test_append_scalar() {
91        let mut builder = NullBuilder::new();
92
93        // Test appending null scalar.
94        let null_scalar = Scalar::null(DType::Null);
95        builder.append_scalar(&null_scalar).unwrap();
96        builder.append_scalar(&null_scalar).unwrap();
97        builder.append_scalar(&null_scalar).unwrap();
98
99        let array = builder.finish();
100        assert_eq!(array.len(), 3);
101
102        // For null arrays, all values are null - nothing to check for actual values.
103        // Just verify the array is indeed a null array with the right length.
104
105        // Test wrong dtype error.
106        let mut builder = NullBuilder::new();
107        let wrong_scalar = Scalar::from(42i32);
108        assert!(builder.append_scalar(&wrong_scalar).is_err());
109    }
110}