Skip to main content

vortex_array/arrays/bool/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hash;
5use std::hash::Hasher;
6
7use kernel::PARENT_KERNELS;
8use prost::Message;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_panic;
14use vortex_session::VortexSession;
15
16use crate::ArrayRef;
17use crate::ExecutionCtx;
18use crate::ExecutionResult;
19use crate::array::Array;
20use crate::array::ArrayParts;
21use crate::array::ArrayView;
22use crate::array::VTable;
23use crate::array::child_to_validity;
24use crate::arrays::bool::BoolData;
25use crate::arrays::bool::array::SLOT_NAMES;
26use crate::buffer::BufferHandle;
27use crate::dtype::DType;
28use crate::serde::ArrayChildren;
29use crate::validity::Validity;
30mod canonical;
31mod kernel;
32mod operations;
33mod validity;
34
35use vortex_session::registry::CachedId;
36
37use crate::EqMode;
38use crate::array::ArrayId;
39use crate::arrays::bool::compute::rules::RULES;
40use crate::hash::ArrayEq;
41use crate::hash::ArrayHash;
42
43/// A [`Bool`]-encoded Vortex array.
44pub type BoolArray = Array<Bool>;
45
46#[derive(prost::Message)]
47pub struct BoolMetadata {
48    // The offset in bits must be <8
49    #[prost(uint32, tag = "1")]
50    pub offset: u32,
51}
52
53impl ArrayHash for BoolData {
54    fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
55        self.bits.array_hash(state, accuracy);
56        self.meta.offset().hash(state);
57    }
58}
59
60impl ArrayEq for BoolData {
61    fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
62        self.meta.offset() == other.meta.offset() && self.bits.array_eq(&other.bits, accuracy)
63    }
64}
65
66impl VTable for Bool {
67    type TypedArrayData = BoolData;
68
69    type OperationsVTable = Self;
70    type ValidityVTable = Self;
71
72    fn id(&self) -> ArrayId {
73        static ID: CachedId = CachedId::new("vortex.bool");
74        *ID
75    }
76
77    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
78        1
79    }
80
81    fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
82        match idx {
83            0 => array.bits.clone(),
84            _ => vortex_panic!("BoolArray buffer index {idx} out of bounds"),
85        }
86    }
87
88    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
89        match idx {
90            0 => Some("bits".to_string()),
91            _ => None,
92        }
93    }
94
95    fn serialize(
96        array: ArrayView<'_, Self>,
97        _session: &VortexSession,
98    ) -> VortexResult<Option<Vec<u8>>> {
99        let offset = array.meta.offset();
100        assert!(offset < 8, "Offset must be <8, got {offset}");
101        Ok(Some(
102            BoolMetadata {
103                offset: u32::try_from(offset).vortex_expect("checked"),
104            }
105            .encode_to_vec(),
106        ))
107    }
108
109    fn validate(
110        &self,
111        data: &BoolData,
112        dtype: &DType,
113        len: usize,
114        slots: &[Option<ArrayRef>],
115    ) -> VortexResult<()> {
116        let DType::Bool(nullability) = dtype else {
117            vortex_bail!("Expected bool dtype, got {dtype:?}");
118        };
119        vortex_ensure!(
120            data.bits.len() * 8 >= data.meta.offset() + len,
121            "BoolArray buffer with offset {} cannot back outer length {} (buffer bits = {})",
122            data.meta.offset(),
123            len,
124            data.bits.len() * 8
125        );
126
127        let validity = child_to_validity(slots[0].as_ref(), *nullability);
128        if let Some(validity_len) = validity.maybe_len() {
129            vortex_ensure!(
130                validity_len == len,
131                "BoolArray validity len {} does not match outer length {}",
132                validity_len,
133                len
134            );
135        }
136
137        Ok(())
138    }
139
140    fn deserialize(
141        &self,
142        dtype: &DType,
143        len: usize,
144        metadata: &[u8],
145        buffers: &[BufferHandle],
146        children: &dyn ArrayChildren,
147        _session: &VortexSession,
148    ) -> VortexResult<ArrayParts<Self>> {
149        let metadata = BoolMetadata::decode(metadata)?;
150        if buffers.len() != 1 {
151            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
152        }
153
154        let validity = if children.is_empty() {
155            Validity::from(dtype.nullability())
156        } else if children.len() == 1 {
157            let validity = children.get(0, &Validity::DTYPE, len)?;
158            Validity::Array(validity)
159        } else {
160            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
161        };
162
163        let buffer = buffers[0].clone();
164        let slots = BoolData::make_slots(&validity, len);
165        let data = BoolData::try_new_from_handle(buffer, metadata.offset as usize, len, validity)?;
166        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
167    }
168
169    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
170        SLOT_NAMES[idx].to_string()
171    }
172
173    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
174        Ok(ExecutionResult::done(array))
175    }
176
177    fn execute_parent(
178        array: ArrayView<'_, Self>,
179        parent: &ArrayRef,
180        child_idx: usize,
181        ctx: &mut ExecutionCtx,
182    ) -> VortexResult<Option<ArrayRef>> {
183        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
184    }
185
186    fn reduce_parent(
187        array: ArrayView<'_, Self>,
188        parent: &ArrayRef,
189        child_idx: usize,
190    ) -> VortexResult<Option<ArrayRef>> {
191        RULES.evaluate(array, parent, child_idx)
192    }
193}
194
195#[derive(Clone, Debug)]
196pub struct Bool;
197
198#[cfg(test)]
199mod tests {
200    use vortex_buffer::ByteBufferMut;
201    use vortex_session::registry::ReadContext;
202
203    use crate::ArrayContext;
204    use crate::IntoArray;
205    use crate::LEGACY_SESSION;
206    use crate::arrays::BoolArray;
207    use crate::assert_arrays_eq;
208    use crate::serde::SerializeOptions;
209    use crate::serde::SerializedArray;
210
211    #[test]
212    fn test_nullable_bool_serde_roundtrip() {
213        let array = BoolArray::from_iter([Some(true), None, Some(false), None]);
214        let dtype = array.dtype().clone();
215        let len = array.len();
216
217        let ctx = ArrayContext::empty();
218        let serialized = array
219            .clone()
220            .into_array()
221            .serialize(&ctx, &LEGACY_SESSION, &SerializeOptions::default())
222            .unwrap();
223
224        let mut concat = ByteBufferMut::empty();
225        for buf in serialized {
226            concat.extend_from_slice(buf.as_ref());
227        }
228        let parts = SerializedArray::try_from(concat.freeze()).unwrap();
229        let decoded = parts
230            .decode(
231                &dtype,
232                len,
233                &ReadContext::new(ctx.to_ids()),
234                &LEGACY_SESSION,
235            )
236            .unwrap();
237
238        assert_arrays_eq!(decoded, array);
239    }
240}