Skip to main content

vortex_array/arrays/listview/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hash;
5use std::sync::Arc;
6
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::Precision;
19use crate::ProstMetadata;
20use crate::SerializeMetadata;
21use crate::arrays::ListViewArray;
22use crate::arrays::listview::compute::rules::PARENT_RULES;
23use crate::buffer::BufferHandle;
24use crate::dtype::DType;
25use crate::dtype::Nullability;
26use crate::dtype::PType;
27use crate::hash::ArrayEq;
28use crate::hash::ArrayHash;
29use crate::serde::ArrayChildren;
30use crate::stats::StatsSetRef;
31use crate::validity::Validity;
32use crate::vtable;
33use crate::vtable::Array;
34use crate::vtable::ArrayId;
35use crate::vtable::VTable;
36use crate::vtable::ValidityVTableFromValidityHelper;
37use crate::vtable::validity_nchildren;
38use crate::vtable::validity_to_child;
39mod operations;
40mod validity;
41vtable!(ListView);
42
43#[derive(Clone, Debug)]
44pub struct ListView;
45
46impl ListView {
47    pub const ID: ArrayId = ArrayId::new_ref("vortex.listview");
48}
49
50#[derive(Clone, prost::Message)]
51pub struct ListViewMetadata {
52    #[prost(uint64, tag = "1")]
53    elements_len: u64,
54    #[prost(enumeration = "PType", tag = "2")]
55    offset_ptype: i32,
56    #[prost(enumeration = "PType", tag = "3")]
57    size_ptype: i32,
58}
59
60impl VTable for ListView {
61    type Array = ListViewArray;
62
63    type Metadata = ProstMetadata<ListViewMetadata>;
64    type OperationsVTable = Self;
65    type ValidityVTable = ValidityVTableFromValidityHelper;
66    fn vtable(_array: &Self::Array) -> &Self {
67        &ListView
68    }
69
70    fn id(&self) -> ArrayId {
71        Self::ID
72    }
73
74    fn len(array: &ListViewArray) -> usize {
75        debug_assert_eq!(array.offsets().len(), array.sizes().len());
76        array.offsets().len()
77    }
78
79    fn dtype(array: &ListViewArray) -> &DType {
80        &array.dtype
81    }
82
83    fn stats(array: &ListViewArray) -> StatsSetRef<'_> {
84        array.stats_set.to_ref(array.as_ref())
85    }
86
87    fn array_hash<H: std::hash::Hasher>(
88        array: &ListViewArray,
89        state: &mut H,
90        precision: Precision,
91    ) {
92        array.dtype.hash(state);
93        array.elements().array_hash(state, precision);
94        array.offsets().array_hash(state, precision);
95        array.sizes().array_hash(state, precision);
96        array.validity.array_hash(state, precision);
97    }
98
99    fn array_eq(array: &ListViewArray, other: &ListViewArray, precision: Precision) -> bool {
100        array.dtype == other.dtype
101            && array.elements().array_eq(other.elements(), precision)
102            && array.offsets().array_eq(other.offsets(), precision)
103            && array.sizes().array_eq(other.sizes(), precision)
104            && array.validity.array_eq(&other.validity, precision)
105    }
106
107    fn nbuffers(_array: &ListViewArray) -> usize {
108        0
109    }
110
111    fn buffer(_array: &ListViewArray, idx: usize) -> BufferHandle {
112        vortex_panic!("ListViewArray buffer index {idx} out of bounds")
113    }
114
115    fn buffer_name(_array: &ListViewArray, idx: usize) -> Option<String> {
116        vortex_panic!("ListViewArray buffer_name index {idx} out of bounds")
117    }
118
119    fn nchildren(array: &ListViewArray) -> usize {
120        3 + validity_nchildren(&array.validity)
121    }
122
123    fn child(array: &ListViewArray, idx: usize) -> ArrayRef {
124        match idx {
125            0 => array.elements().clone(),
126            1 => array.offsets().clone(),
127            2 => array.sizes().clone(),
128            3 => validity_to_child(&array.validity, array.len())
129                .vortex_expect("ListViewArray validity child out of bounds"),
130            _ => vortex_panic!("ListViewArray child index {idx} out of bounds"),
131        }
132    }
133
134    fn child_name(_array: &ListViewArray, idx: usize) -> String {
135        match idx {
136            0 => "elements".to_string(),
137            1 => "offsets".to_string(),
138            2 => "sizes".to_string(),
139            3 => "validity".to_string(),
140            _ => vortex_panic!("ListViewArray child_name index {idx} out of bounds"),
141        }
142    }
143
144    fn metadata(array: &ListViewArray) -> VortexResult<Self::Metadata> {
145        Ok(ProstMetadata(ListViewMetadata {
146            elements_len: array.elements().len() as u64,
147            offset_ptype: PType::try_from(array.offsets().dtype())? as i32,
148            size_ptype: PType::try_from(array.sizes().dtype())? as i32,
149        }))
150    }
151
152    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
153        Ok(Some(metadata.serialize()))
154    }
155
156    fn deserialize(
157        bytes: &[u8],
158        _dtype: &DType,
159        _len: usize,
160        _buffers: &[BufferHandle],
161        _session: &VortexSession,
162    ) -> VortexResult<Self::Metadata> {
163        let metadata = <Self::Metadata as DeserializeMetadata>::deserialize(bytes)?;
164        Ok(ProstMetadata(metadata))
165    }
166
167    fn build(
168        dtype: &DType,
169        len: usize,
170        metadata: &Self::Metadata,
171        buffers: &[BufferHandle],
172        children: &dyn ArrayChildren,
173    ) -> VortexResult<ListViewArray> {
174        vortex_ensure!(
175            buffers.is_empty(),
176            "`ListViewArray::build` expects no buffers"
177        );
178
179        let DType::List(element_dtype, _) = dtype else {
180            vortex_bail!("Expected List dtype, got {:?}", dtype);
181        };
182
183        let validity = if children.len() == 3 {
184            Validity::from(dtype.nullability())
185        } else if children.len() == 4 {
186            let validity = children.get(3, &Validity::DTYPE, len)?;
187            Validity::Array(validity)
188        } else {
189            vortex_bail!(
190                "`ListViewArray::build` expects 3 or 4 children, got {}",
191                children.len()
192            );
193        };
194
195        // Get elements with the correct length from metadata.
196        let elements = children.get(
197            0,
198            element_dtype.as_ref(),
199            usize::try_from(metadata.0.elements_len)?,
200        )?;
201
202        // Get offsets with proper type from metadata.
203        let offsets = children.get(
204            1,
205            &DType::Primitive(metadata.0.offset_ptype(), Nullability::NonNullable),
206            len,
207        )?;
208
209        // Get sizes with proper type from metadata.
210        let sizes = children.get(
211            2,
212            &DType::Primitive(metadata.0.size_ptype(), Nullability::NonNullable),
213            len,
214        )?;
215
216        ListViewArray::try_new(elements, offsets, sizes, validity)
217    }
218
219    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
220        vortex_ensure!(
221            children.len() == 3 || children.len() == 4,
222            "ListViewArray expects 3 or 4 children, got {}",
223            children.len()
224        );
225
226        let mut iter = children.into_iter();
227        let elements = iter
228            .next()
229            .vortex_expect("children length already validated");
230        let offsets = iter
231            .next()
232            .vortex_expect("children length already validated");
233        let sizes = iter
234            .next()
235            .vortex_expect("children length already validated");
236        let validity = if let Some(validity_array) = iter.next() {
237            Validity::Array(validity_array)
238        } else {
239            Validity::from(array.dtype.nullability())
240        };
241
242        let new_array = ListViewArray::try_new(elements, offsets, sizes, validity)?;
243        *array = new_array;
244        Ok(())
245    }
246
247    fn execute(array: Arc<Array<Self>>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
248        Ok(ExecutionResult::done(array))
249    }
250
251    fn reduce_parent(
252        array: &Array<Self>,
253        parent: &ArrayRef,
254        child_idx: usize,
255    ) -> VortexResult<Option<ArrayRef>> {
256        PARENT_RULES.evaluate(array, parent, child_idx)
257    }
258}