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