vortex_array/arrays/list/vtable/
serde.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::ByteBuffer;
5use vortex_dtype::{DType, Nullability, PType};
6use vortex_error::{VortexResult, vortex_bail};
7
8use super::ListArray;
9use crate::ProstMetadata;
10use crate::arrays::{ListEncoding, ListVTable};
11use crate::serde::ArrayChildren;
12use crate::validity::Validity;
13use crate::vtable::SerdeVTable;
14
15#[derive(Clone, prost::Message)]
16pub struct ListMetadata {
17    #[prost(uint64, tag = "1")]
18    elements_len: u64,
19    #[prost(enumeration = "PType", tag = "2")]
20    offset_ptype: i32,
21}
22
23impl SerdeVTable<ListVTable> for ListVTable {
24    type Metadata = ProstMetadata<ListMetadata>;
25
26    fn metadata(array: &ListArray) -> VortexResult<Option<Self::Metadata>> {
27        Ok(Some(ProstMetadata(ListMetadata {
28            elements_len: array.elements().len() as u64,
29            offset_ptype: PType::try_from(array.offsets().dtype())? as i32,
30        })))
31    }
32
33    fn build(
34        _encoding: &ListEncoding,
35        dtype: &DType,
36        len: usize,
37        metadata: &ListMetadata,
38        _buffers: &[ByteBuffer],
39        children: &dyn ArrayChildren,
40    ) -> VortexResult<ListArray> {
41        let validity = if children.len() == 2 {
42            Validity::from(dtype.nullability())
43        } else if children.len() == 3 {
44            let validity = children.get(2, &Validity::DTYPE, len)?;
45            Validity::Array(validity)
46        } else {
47            vortex_bail!("Expected 2 or 3 children, got {}", children.len());
48        };
49
50        let DType::List(element_dtype, _) = &dtype else {
51            vortex_bail!("Expected List dtype, got {:?}", dtype);
52        };
53        let elements = children.get(
54            0,
55            element_dtype.as_ref(),
56            usize::try_from(metadata.elements_len)?,
57        )?;
58
59        let offsets = children.get(
60            1,
61            &DType::Primitive(metadata.offset_ptype(), Nullability::NonNullable),
62            len + 1,
63        )?;
64
65        ListArray::try_new(elements, offsets, validity)
66    }
67}