Skip to main content

astrs_data/array/
null.rs

1//! [`NullArray`] — the type whose every value is null and whose every buffer
2//! is absent.
3//!
4//! Arrow's `Null` type carries no validity bitmap and no values buffer at all;
5//! the length alone is the entire representation. AstRS uses it for ports
6//! declared `type: any` that never carry data, and stage 2 encodes it as a
7//! record-batch node with zero buffers.
8//!
9//! ```
10//! use astrs_data::array::{Array, NullArray};
11//!
12//! let nulls = NullArray::new(3);
13//! assert_eq!(nulls.len(), 3);
14//! assert_eq!(nulls.null_count(), 3);
15//! assert_eq!(nulls.buffer_memory_size(), 0, "no buffers at all");
16//! assert!(nulls.is_null(0));
17//! ```
18
19use std::any::Any;
20use std::fmt;
21use std::sync::Arc;
22
23use crate::array::iter::{ArrayAccessor, ArrayIter};
24use crate::array::{Array, ArrayRef, NULL_TYPE, clamp_window};
25use crate::buffer::Bitmap;
26use crate::datatype::DataType;
27use crate::error::{DataError, Result};
28use crate::sealed::Sealed;
29
30/// A column of `len` nulls and nothing else.
31#[derive(Clone, PartialEq, Eq)]
32pub struct NullArray {
33    /// Logical length. The whole representation.
34    len: usize,
35}
36
37impl NullArray {
38    /// A column of `len` nulls.
39    #[inline]
40    #[must_use]
41    pub const fn new(len: usize) -> Self {
42        Self { len }
43    }
44
45    /// Always `None`; present so the accessor shape matches the other
46    /// families.
47    #[inline]
48    #[must_use]
49    pub const fn get(&self, _index: usize) -> Option<()> {
50        None
51    }
52
53    /// Iterates, yielding `None` `len` times.
54    #[inline]
55    pub fn iter(&self) -> ArrayIter<&Self> {
56        ArrayIter::new(self)
57    }
58
59    /// A sub-range, clamped to the array (the crate-wide slicing convention).
60    #[must_use]
61    pub fn slice(&self, offset: usize, len: usize) -> Self {
62        let (_, len) = clamp_window(self.len, offset, len);
63        Self { len }
64    }
65
66    /// Checked [`NullArray::slice`].
67    ///
68    /// # Errors
69    ///
70    /// [`DataError::SliceOutOfBounds`] when the window leaves the array.
71    pub fn try_slice(&self, offset: usize, len: usize) -> Result<Self> {
72        if offset.saturating_add(len) > self.len {
73            return Err(DataError::SliceOutOfBounds {
74                offset,
75                len,
76                available: self.len,
77            });
78        }
79        Ok(self.slice(offset, len))
80    }
81}
82
83impl Sealed for NullArray {}
84
85impl Array for NullArray {
86    fn as_any(&self) -> &dyn Any {
87        self
88    }
89
90    fn data_type(&self) -> &DataType {
91        &NULL_TYPE
92    }
93
94    fn len(&self) -> usize {
95        self.len
96    }
97
98    fn validity(&self) -> Option<&Bitmap> {
99        // The Null type has no validity buffer; `null_count` is overridden
100        // instead so callers still see every slot as null.
101        None
102    }
103
104    fn null_count(&self) -> usize {
105        self.len
106    }
107
108    fn is_valid(&self, _index: usize) -> bool {
109        false
110    }
111
112    fn slice(&self, offset: usize, len: usize) -> ArrayRef {
113        Arc::new(Self::slice(self, offset, len))
114    }
115
116    fn buffer_memory_size(&self) -> usize {
117        0
118    }
119
120    fn equals(&self, other: &dyn Array) -> bool {
121        other
122            .as_any()
123            .downcast_ref::<Self>()
124            .is_some_and(|other| self.len == other.len)
125    }
126}
127
128impl ArrayAccessor for &NullArray {
129    type Item = ();
130
131    #[inline]
132    fn accessor_len(&self) -> usize {
133        self.len
134    }
135
136    #[inline]
137    fn accessor_get(&self, _index: usize) -> Option<()> {
138        None
139    }
140}
141
142impl<'a> IntoIterator for &'a NullArray {
143    type Item = Option<()>;
144    type IntoIter = ArrayIter<&'a NullArray>;
145
146    fn into_iter(self) -> Self::IntoIter {
147        self.iter()
148    }
149}
150
151impl fmt::Debug for NullArray {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(f, "NullArray[Null; len={}]", self.len)
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
160
161    use super::*;
162
163    #[test]
164    fn empty_null_array() {
165        let array = NullArray::new(0);
166        assert!(array.is_empty());
167        assert_eq!(array.null_count(), 0);
168        assert_eq!(array.iter().count(), 0);
169    }
170
171    #[test]
172    fn every_slot_is_null() {
173        let array = NullArray::new(4);
174        assert_eq!(array.len(), 4);
175        assert_eq!(array.null_count(), 4);
176        assert!(array.validity().is_none());
177        for index in 0..5 {
178            assert!(array.is_null(index));
179            assert!(!array.is_valid(index));
180            assert_eq!(array.get(index), None);
181        }
182        assert_eq!(array.iter().collect::<Vec<_>>(), vec![None; 4]);
183    }
184
185    #[test]
186    fn slicing_only_changes_the_length() {
187        let array = NullArray::new(10);
188        assert_eq!(array.slice(3, 4).len(), 4);
189        assert_eq!(array.slice(8, 99).len(), 2);
190        assert_eq!(array.slice(99, 1).len(), 0);
191        assert_eq!(array.try_slice(3, 4).unwrap().len(), 4);
192        assert_eq!(
193            array.try_slice(8, 5).unwrap_err(),
194            DataError::SliceOutOfBounds {
195                offset: 8,
196                len: 5,
197                available: 10
198            }
199        );
200    }
201
202    #[test]
203    fn carries_no_buffers() {
204        assert_eq!(NullArray::new(1_000_000).buffer_memory_size(), 0);
205    }
206
207    #[test]
208    fn equality_is_by_length() {
209        assert_eq!(NullArray::new(3), NullArray::new(3));
210        assert_ne!(NullArray::new(3), NullArray::new(4));
211        let other: ArrayRef = Arc::new(crate::array::Int32Array::from_values([1]));
212        assert!(!NullArray::new(1).equals(other.as_ref()));
213    }
214
215    #[test]
216    fn debug_output() {
217        assert_eq!(format!("{:?}", NullArray::new(7)), "NullArray[Null; len=7]");
218    }
219
220    #[test]
221    fn trait_object_round_trip() {
222        let array: ArrayRef = Arc::new(NullArray::new(5));
223        assert_eq!(array.data_type(), &DataType::Null);
224        assert_eq!(array.slice(1, 2).len(), 2);
225        assert_eq!((&NullArray::new(2)).into_iter().count(), 2);
226    }
227}