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