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_ensure_eq;
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::BoolSlots;
26use crate::buffer::BufferHandle;
27use crate::builders::ArrayBuilder;
28use crate::builders::BoolBuilder;
29use crate::dtype::DType;
30use crate::serde::ArrayChildren;
31use crate::validity::Validity;
32mod kernel;
33mod operations;
34mod validity;
35
36use vortex_session::registry::CachedId;
37
38use crate::EqMode;
39use crate::array::ArrayId;
40use crate::arrays::bool::compute::rules::RULES;
41use crate::hash::ArrayEq;
42use crate::hash::ArrayHash;
43
44/// A [`Bool`]-encoded Vortex array.
45pub type BoolArray = Array<Bool>;
46
47pub(crate) fn initialize(session: &VortexSession) {
48    kernel::initialize(session);
49}
50
51#[derive(prost::Message)]
52pub struct BoolMetadata {
53    // The offset in bits must be <8
54    #[prost(uint32, tag = "1")]
55    pub offset: u32,
56}
57
58impl ArrayHash for BoolData {
59    fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
60        self.bits.array_hash(state, accuracy);
61        self.meta.offset().hash(state);
62    }
63}
64
65impl ArrayEq for BoolData {
66    fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
67        self.meta.offset() == other.meta.offset() && self.bits.array_eq(&other.bits, accuracy)
68    }
69}
70
71impl VTable for Bool {
72    type TypedArrayData = BoolData;
73
74    type OperationsVTable = Self;
75    type ValidityVTable = Self;
76
77    fn id(&self) -> ArrayId {
78        static ID: CachedId = CachedId::new("vortex.bool");
79        *ID
80    }
81
82    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
83        1
84    }
85
86    fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
87        match idx {
88            0 => array.bits.clone(),
89            _ => vortex_panic!("BoolArray buffer index {idx} out of bounds"),
90        }
91    }
92
93    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
94        match idx {
95            0 => Some("bits".to_string()),
96            _ => None,
97        }
98    }
99
100    fn with_buffers(
101        &self,
102        array: ArrayView<'_, Self>,
103        buffers: &[BufferHandle],
104    ) -> VortexResult<ArrayParts<Self>> {
105        vortex_ensure_eq!(buffers.len(), 1);
106        let mut data = array.data().clone();
107        data.bits = buffers[0].clone();
108        Ok(ArrayParts::new(
109            self.clone(),
110            array.dtype().clone(),
111            array.len(),
112            data,
113            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[BoolSlots::VALIDITY].as_ref(), *nullability);
150        if let Some(validity_len) = validity.maybe_len() {
151            vortex_ensure_eq!(
152                validity_len,
153                len,
154                "BoolArray validity len does not match outer length",
155            );
156        }
157
158        Ok(())
159    }
160
161    fn deserialize(
162        &self,
163        dtype: &DType,
164        len: usize,
165        metadata: &[u8],
166        buffers: &[BufferHandle],
167        children: &dyn ArrayChildren,
168        _session: &VortexSession,
169    ) -> VortexResult<ArrayParts<Self>> {
170        let metadata = BoolMetadata::decode(metadata)?;
171        if buffers.len() != 1 {
172            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
173        }
174
175        let validity = if children.is_empty() {
176            Validity::from(dtype.nullability())
177        } else if children.len() == 1 {
178            let validity = children.get(0, &Validity::DTYPE, len)?;
179            Validity::Array(validity)
180        } else {
181            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
182        };
183
184        let buffer = buffers[0].clone();
185        let slots = BoolData::make_slots(&validity, len);
186        let data = BoolData::try_new_from_handle(buffer, metadata.offset as usize, len, validity)?;
187        Ok(ArrayParts::new(
188            self.clone(),
189            dtype.clone(),
190            len,
191            data,
192            slots,
193        ))
194    }
195
196    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
197        BoolSlots::NAMES[idx].to_string()
198    }
199
200    fn append_to_builder(
201        array: ArrayView<'_, Self>,
202        builder: &mut dyn ArrayBuilder,
203        ctx: &mut ExecutionCtx,
204    ) -> VortexResult<()> {
205        let Some(builder) = builder.as_any_mut().downcast_mut::<BoolBuilder>() else {
206            vortex_bail!("append_to_builder for Bool requires a BoolBuilder");
207        };
208        builder.append_bool_array(&array.into_owned(), ctx)
209    }
210
211    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
212        Ok(ExecutionResult::done(array))
213    }
214
215    fn reduce_parent(
216        array: ArrayView<'_, Self>,
217        parent: &ArrayRef,
218        child_idx: usize,
219    ) -> VortexResult<Option<ArrayRef>> {
220        RULES.evaluate(array, parent, child_idx)
221    }
222}
223
224#[derive(Clone, Debug)]
225pub struct Bool;
226
227#[cfg(test)]
228mod tests {
229    use vortex_buffer::ByteBufferMut;
230    use vortex_session::registry::ReadContext;
231
232    use crate::ArrayContext;
233    use crate::IntoArray;
234    use crate::VortexSessionExecute;
235    use crate::array_session;
236    use crate::arrays::BoolArray;
237    use crate::assert_arrays_eq;
238    use crate::serde::SerializeOptions;
239    use crate::serde::SerializedArray;
240
241    #[test]
242    fn test_nullable_bool_serde_roundtrip() {
243        let session = array_session();
244        let mut ctx = session.create_execution_ctx();
245        let array = BoolArray::from_iter([Some(true), None, Some(false), None]);
246        let dtype = array.dtype().clone();
247        let len = array.len();
248
249        let array_ctx = ArrayContext::empty();
250        let serialized = array
251            .clone()
252            .into_array()
253            .serialize(&array_ctx, &session, &SerializeOptions::default())
254            .unwrap();
255
256        let mut concat = ByteBufferMut::empty();
257        for buf in serialized {
258            concat.extend_from_slice(buf.as_ref());
259        }
260        let parts = SerializedArray::try_from(concat.freeze()).unwrap();
261        let decoded = parts
262            .decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &session)
263            .unwrap();
264
265        assert_arrays_eq!(decoded, array, &mut ctx);
266    }
267}