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::sync::Arc;
5
6use kernel::PARENT_KERNELS;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_ensure;
11use vortex_error::vortex_panic;
12use vortex_session::VortexSession;
13
14use crate::ArrayRef;
15use crate::DeserializeMetadata;
16use crate::ExecutionCtx;
17use crate::ExecutionResult;
18use crate::ProstMetadata;
19use crate::SerializeMetadata;
20use crate::arrays::BoolArray;
21use crate::buffer::BufferHandle;
22use crate::dtype::DType;
23use crate::serde::ArrayChildren;
24use crate::validity::Validity;
25use crate::vtable;
26use crate::vtable::Array;
27use crate::vtable::VTable;
28use crate::vtable::ValidityVTableFromValidityHelper;
29use crate::vtable::validity_nchildren;
30use crate::vtable::validity_to_child;
31mod canonical;
32mod kernel;
33mod operations;
34mod validity;
35
36use std::hash::Hash;
37
38use crate::Precision;
39use crate::arrays::bool::compute::rules::RULES;
40use crate::hash::ArrayEq;
41use crate::hash::ArrayHash;
42use crate::stats::StatsSetRef;
43use crate::vtable::ArrayId;
44
45vtable!(Bool);
46
47#[derive(prost::Message)]
48pub struct BoolMetadata {
49    // The offset in bits must be <8
50    #[prost(uint32, tag = "1")]
51    pub offset: u32,
52}
53
54impl VTable for Bool {
55    type Array = BoolArray;
56
57    type Metadata = ProstMetadata<BoolMetadata>;
58    type OperationsVTable = Self;
59    type ValidityVTable = ValidityVTableFromValidityHelper;
60
61    fn vtable(_array: &Self::Array) -> &Self {
62        &Bool
63    }
64
65    fn id(&self) -> ArrayId {
66        Self::ID
67    }
68
69    fn len(array: &BoolArray) -> usize {
70        array.len
71    }
72
73    fn dtype(array: &BoolArray) -> &DType {
74        &array.dtype
75    }
76
77    fn stats(array: &BoolArray) -> StatsSetRef<'_> {
78        array.stats_set.to_ref(array.as_ref())
79    }
80
81    fn array_hash<H: std::hash::Hasher>(array: &BoolArray, state: &mut H, precision: Precision) {
82        array.dtype.hash(state);
83        array.to_bit_buffer().array_hash(state, precision);
84        array.validity.array_hash(state, precision);
85    }
86
87    fn array_eq(array: &BoolArray, other: &BoolArray, precision: Precision) -> bool {
88        if array.dtype != other.dtype {
89            return false;
90        }
91        array
92            .to_bit_buffer()
93            .array_eq(&other.to_bit_buffer(), precision)
94            && array.validity.array_eq(&other.validity, precision)
95    }
96
97    fn nbuffers(_array: &BoolArray) -> usize {
98        1
99    }
100
101    fn buffer(array: &BoolArray, idx: usize) -> BufferHandle {
102        match idx {
103            0 => array.bits.clone(),
104            _ => vortex_panic!("BoolArray buffer index {idx} out of bounds"),
105        }
106    }
107
108    fn buffer_name(_array: &BoolArray, idx: usize) -> Option<String> {
109        match idx {
110            0 => Some("bits".to_string()),
111            _ => None,
112        }
113    }
114
115    fn nchildren(array: &BoolArray) -> usize {
116        validity_nchildren(&array.validity)
117    }
118
119    fn child(array: &BoolArray, idx: usize) -> ArrayRef {
120        match idx {
121            0 => validity_to_child(&array.validity, array.len())
122                .vortex_expect("BoolArray child index out of bounds"),
123            _ => vortex_panic!("BoolArray child index {idx} out of bounds"),
124        }
125    }
126
127    fn child_name(_array: &BoolArray, _idx: usize) -> String {
128        "validity".to_string()
129    }
130
131    fn metadata(array: &BoolArray) -> VortexResult<Self::Metadata> {
132        assert!(array.offset < 8, "Offset must be <8, got {}", array.offset);
133        Ok(ProstMetadata(BoolMetadata {
134            offset: u32::try_from(array.offset).vortex_expect("checked"),
135        }))
136    }
137
138    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
139        Ok(Some(metadata.serialize()))
140    }
141
142    fn deserialize(
143        bytes: &[u8],
144        _dtype: &DType,
145        _len: usize,
146        _buffers: &[BufferHandle],
147        _session: &VortexSession,
148    ) -> VortexResult<Self::Metadata> {
149        let metadata = <Self::Metadata as DeserializeMetadata>::deserialize(bytes)?;
150        Ok(ProstMetadata(metadata))
151    }
152
153    fn build(
154        dtype: &DType,
155        len: usize,
156        metadata: &Self::Metadata,
157        buffers: &[BufferHandle],
158        children: &dyn ArrayChildren,
159    ) -> VortexResult<BoolArray> {
160        if buffers.len() != 1 {
161            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
162        }
163
164        let validity = if children.is_empty() {
165            Validity::from(dtype.nullability())
166        } else if children.len() == 1 {
167            let validity = children.get(0, &Validity::DTYPE, len)?;
168            Validity::Array(validity)
169        } else {
170            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
171        };
172
173        let buffer = buffers[0].clone();
174
175        BoolArray::try_new_from_handle(buffer, metadata.offset as usize, len, validity)
176    }
177
178    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
179        vortex_ensure!(
180            children.len() <= 1,
181            "BoolArray can have at most 1 child (validity), got {}",
182            children.len()
183        );
184
185        array.validity = if children.is_empty() {
186            Validity::from(array.dtype().nullability())
187        } else {
188            Validity::Array(children.into_iter().next().vortex_expect("checked"))
189        };
190
191        Ok(())
192    }
193
194    fn execute(array: Arc<Array<Self>>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
195        Ok(ExecutionResult::done(array))
196    }
197
198    fn execute_parent(
199        array: &Array<Self>,
200        parent: &ArrayRef,
201        child_idx: usize,
202        ctx: &mut ExecutionCtx,
203    ) -> VortexResult<Option<ArrayRef>> {
204        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
205    }
206
207    fn reduce_parent(
208        array: &Array<Self>,
209        parent: &ArrayRef,
210        child_idx: usize,
211    ) -> VortexResult<Option<ArrayRef>> {
212        RULES.evaluate(array, parent, child_idx)
213    }
214}
215
216#[derive(Clone, Debug)]
217pub struct Bool;
218
219impl Bool {
220    pub const ID: ArrayId = ArrayId::new_ref("vortex.bool");
221}