vortex_array/arrays/bool/vtable/
mod.rs1use 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 canonical;
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
44pub 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 #[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!(
106 buffers.len() == 1,
107 "Expected 1 buffer, got {}",
108 buffers.len()
109 );
110 let mut data = array.data().clone();
111 data.bits = buffers[0].clone();
112 Ok(
113 ArrayParts::new(self.clone(), array.dtype().clone(), array.len(), data)
114 .with_slots(array.slots().iter().cloned().collect()),
115 )
116 }
117
118 fn serialize(
119 array: ArrayView<'_, Self>,
120 _session: &VortexSession,
121 ) -> VortexResult<Option<Vec<u8>>> {
122 let offset = array.meta.offset();
123 assert!(offset < 8, "Offset must be <8, got {offset}");
124 Ok(Some(
125 BoolMetadata {
126 offset: u32::try_from(offset).vortex_expect("checked"),
127 }
128 .encode_to_vec(),
129 ))
130 }
131
132 fn validate(
133 &self,
134 data: &BoolData,
135 dtype: &DType,
136 len: usize,
137 slots: &[Option<ArrayRef>],
138 ) -> VortexResult<()> {
139 let DType::Bool(nullability) = dtype else {
140 vortex_bail!("Expected bool dtype, got {dtype:?}");
141 };
142 vortex_ensure!(
143 data.bits.len() * 8 >= data.meta.offset() + len,
144 "BoolArray buffer with offset {} cannot back outer length {} (buffer bits = {})",
145 data.meta.offset(),
146 len,
147 data.bits.len() * 8
148 );
149
150 let validity = child_to_validity(slots[0].as_ref(), *nullability);
151 if let Some(validity_len) = validity.maybe_len() {
152 vortex_ensure!(
153 validity_len == len,
154 "BoolArray validity len {} does not match outer length {}",
155 validity_len,
156 len
157 );
158 }
159
160 Ok(())
161 }
162
163 fn deserialize(
164 &self,
165 dtype: &DType,
166 len: usize,
167 metadata: &[u8],
168 buffers: &[BufferHandle],
169 children: &dyn ArrayChildren,
170 _session: &VortexSession,
171 ) -> VortexResult<ArrayParts<Self>> {
172 let metadata = BoolMetadata::decode(metadata)?;
173 if buffers.len() != 1 {
174 vortex_bail!("Expected 1 buffer, got {}", buffers.len());
175 }
176
177 let validity = if children.is_empty() {
178 Validity::from(dtype.nullability())
179 } else if children.len() == 1 {
180 let validity = children.get(0, &Validity::DTYPE, len)?;
181 Validity::Array(validity)
182 } else {
183 vortex_bail!("Expected 0 or 1 child, got {}", children.len());
184 };
185
186 let buffer = buffers[0].clone();
187 let slots = BoolData::make_slots(&validity, len);
188 let data = BoolData::try_new_from_handle(buffer, metadata.offset as usize, len, validity)?;
189 Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
190 }
191
192 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
193 SLOT_NAMES[idx].to_string()
194 }
195
196 fn append_to_builder(
197 array: ArrayView<'_, Self>,
198 builder: &mut dyn ArrayBuilder,
199 ctx: &mut ExecutionCtx,
200 ) -> VortexResult<()> {
201 if let Some(builder) = builder.as_any_mut().downcast_mut::<BoolBuilder>() {
202 return builder.append_bool_array(&array.into_owned(), ctx);
203 }
204
205 builder.extend_from_array(array.as_ref());
206 Ok(())
207 }
208
209 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
210 Ok(ExecutionResult::done(array))
211 }
212
213 fn reduce_parent(
214 array: ArrayView<'_, Self>,
215 parent: &ArrayRef,
216 child_idx: usize,
217 ) -> VortexResult<Option<ArrayRef>> {
218 RULES.evaluate(array, parent, child_idx)
219 }
220}
221
222#[derive(Clone, Debug)]
223pub struct Bool;
224
225#[cfg(test)]
226mod tests {
227 use vortex_buffer::ByteBufferMut;
228 use vortex_session::registry::ReadContext;
229
230 use crate::ArrayContext;
231 use crate::IntoArray;
232 use crate::VortexSessionExecute;
233 use crate::array_session;
234 use crate::arrays::BoolArray;
235 use crate::assert_arrays_eq;
236 use crate::serde::SerializeOptions;
237 use crate::serde::SerializedArray;
238
239 #[test]
240 fn test_nullable_bool_serde_roundtrip() {
241 let session = array_session();
242 let mut ctx = session.create_execution_ctx();
243 let array = BoolArray::from_iter([Some(true), None, Some(false), None]);
244 let dtype = array.dtype().clone();
245 let len = array.len();
246
247 let array_ctx = ArrayContext::empty();
248 let serialized = array
249 .clone()
250 .into_array()
251 .serialize(&array_ctx, &session, &SerializeOptions::default())
252 .unwrap();
253
254 let mut concat = ByteBufferMut::empty();
255 for buf in serialized {
256 concat.extend_from_slice(buf.as_ref());
257 }
258 let parts = SerializedArray::try_from(concat.freeze()).unwrap();
259 let decoded = parts
260 .decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &session)
261 .unwrap();
262
263 assert_arrays_eq!(decoded, array, &mut ctx);
264 }
265}