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