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