vortex_array/arrays/bool/vtable/
mod.rs1use std::hash::Hash;
5use std::hash::Hasher;
6
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_error::vortex_ensure_eq;
11use vortex_error::vortex_panic;
12use vortex_session::VortexSession;
13
14use crate::ArrayRef;
15use crate::ExecutionCtx;
16use crate::ExecutionResult;
17use crate::array::Array;
18use crate::array::ArrayParts;
19use crate::array::ArrayView;
20use crate::array::VTable;
21use crate::array::child_to_validity;
22use crate::arrays::bool::BoolData;
23use crate::arrays::bool::array::BoolSlots;
24use crate::buffer::BufferHandle;
25use crate::builders::ArrayBuilder;
26use crate::builders::BoolBuilder;
27use crate::dtype::DType;
28mod kernel;
29mod operations;
30mod plugin;
31mod validity;
32
33use vortex_session::registry::CachedId;
34
35use crate::EqMode;
36use crate::array::ArrayId;
37use crate::hash::ArrayEq;
38use crate::hash::ArrayHash;
39
40pub type BoolArray = Array<Bool>;
42
43pub(crate) fn initialize(session: &VortexSession) {
44 kernel::initialize(session);
45}
46
47#[derive(prost::Message)]
48pub struct BoolMetadata {
49 #[prost(uint32, tag = "1")]
51 pub(crate) offset: u32,
52}
53
54impl ArrayHash for BoolData {
55 fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
56 self.bits.array_hash(state, accuracy);
57 self.meta.offset().hash(state);
58 }
59}
60
61impl ArrayEq for BoolData {
62 fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
63 self.meta.offset() == other.meta.offset() && self.bits.array_eq(&other.bits, accuracy)
64 }
65}
66
67impl VTable for Bool {
68 type TypedArrayData = BoolData;
69
70 type OperationsVTable = Self;
71 type ValidityVTable = Self;
72
73 fn id(&self) -> ArrayId {
74 static ID: CachedId = CachedId::new("vortex.bool");
75 *ID
76 }
77
78 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
79 1
80 }
81
82 fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
83 match idx {
84 0 => array.bits.clone(),
85 _ => vortex_panic!("BoolArray buffer index {idx} out of bounds"),
86 }
87 }
88
89 fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
90 match idx {
91 0 => Some("bits".to_string()),
92 _ => None,
93 }
94 }
95
96 fn with_buffers(
97 &self,
98 array: ArrayView<'_, Self>,
99 buffers: &[BufferHandle],
100 ) -> VortexResult<ArrayParts<Self>> {
101 vortex_ensure_eq!(buffers.len(), 1);
102 let mut data = array.data().clone();
103 data.bits = buffers[0].clone();
104 Ok(ArrayParts::new(
105 self.clone(),
106 array.dtype().clone(),
107 array.len(),
108 data,
109 array.slots().iter().cloned().collect(),
110 ))
111 }
112
113 fn validate(
114 &self,
115 data: &BoolData,
116 dtype: &DType,
117 len: usize,
118 slots: &[Option<ArrayRef>],
119 ) -> VortexResult<()> {
120 let DType::Bool(nullability) = dtype else {
121 vortex_bail!("Expected bool dtype, got {dtype:?}");
122 };
123 vortex_ensure!(
124 data.bits.len() * 8 >= data.meta.offset() + len,
125 "BoolArray buffer with offset {} cannot back outer length {} (buffer bits = {})",
126 data.meta.offset(),
127 len,
128 data.bits.len() * 8
129 );
130
131 let validity = child_to_validity(slots[BoolSlots::VALIDITY_CHILD].as_ref(), *nullability);
132 if let Some(validity_len) = validity.maybe_len() {
133 vortex_ensure_eq!(
134 validity_len,
135 len,
136 "BoolArray validity len does not match outer length",
137 );
138 }
139
140 Ok(())
141 }
142
143 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
144 BoolSlots::NAMES[idx].to_string()
145 }
146
147 fn append_to_builder(
148 array: ArrayView<'_, Self>,
149 builder: &mut dyn ArrayBuilder,
150 ctx: &mut ExecutionCtx,
151 ) -> VortexResult<()> {
152 let Some(builder) = builder.as_any_mut().downcast_mut::<BoolBuilder>() else {
153 vortex_bail!("append_to_builder for Bool requires a BoolBuilder");
154 };
155 builder.append_bool_array(array, ctx)
156 }
157
158 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
159 Ok(ExecutionResult::done(array))
160 }
161}
162
163#[derive(Clone, Debug)]
164pub struct Bool;
165
166#[cfg(test)]
167mod tests {
168 use std::sync::LazyLock;
169
170 use vortex_buffer::ByteBufferMut;
171 use vortex_session::VortexSession;
172 use vortex_session::registry::ReadContext;
173
174 use crate::ArrayContext;
175 use crate::IntoArray;
176 use crate::VortexSessionExecute;
177 use crate::arrays::BoolArray;
178 use crate::assert_arrays_eq;
179 use crate::serde::SerializeOptions;
180 use crate::serde::SerializedArray;
181
182 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
183
184 #[test]
185 fn test_nullable_bool_serde_roundtrip() {
186 let mut ctx = SESSION.create_execution_ctx();
187 let array = BoolArray::from_iter([Some(true), None, Some(false), None]);
188 let dtype = array.dtype().clone();
189 let len = array.len();
190
191 let array_ctx = ArrayContext::empty();
192 let serialized = array
193 .clone()
194 .into_array()
195 .serialize(&array_ctx, &SESSION, &SerializeOptions::default())
196 .unwrap();
197
198 let mut concat = ByteBufferMut::empty();
199 for buf in serialized {
200 concat.extend_from_slice(buf.as_ref());
201 }
202 let parts = SerializedArray::try_from(concat.freeze()).unwrap();
203 let decoded = parts
204 .decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &SESSION)
205 .unwrap();
206
207 assert_arrays_eq!(decoded, array, &mut ctx);
208 }
209}