Skip to main content

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