vortex_array/arrays/list/
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, ListVTable};
9use crate::arrays::ListEncoding;
10use crate::serde::ArrayChildren;
11use crate::validity::Validity;
12use crate::vtable::{SerdeVTable, ValidityHelper, VisitorVTable};
13use crate::{Array, ArrayBufferVisitor, ArrayChildVisitor, ProstMetadata};
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}
68
69impl VisitorVTable<ListVTable> for ListVTable {
70    fn visit_buffers(_array: &ListArray, _visitor: &mut dyn ArrayBufferVisitor) {}
71
72    fn visit_children(array: &ListArray, visitor: &mut dyn ArrayChildVisitor) {
73        visitor.visit_child("elements", array.elements());
74        visitor.visit_child("offsets", array.offsets());
75        visitor.visit_validity(array.validity(), array.len());
76    }
77}