vortex_zigzag/
serde.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::serde::ArrayChildren;
5use vortex_array::vtable::{EncodeVTable, SerdeVTable, VisitorVTable};
6use vortex_array::{
7    ArrayBufferVisitor, ArrayChildVisitor, Canonical, DeserializeMetadata, EmptyMetadata,
8};
9use vortex_buffer::ByteBuffer;
10use vortex_dtype::{DType, PType};
11use vortex_error::{VortexResult, vortex_bail};
12
13use crate::{ZigZagArray, ZigZagEncoding, ZigZagVTable, zigzag_encode};
14
15impl SerdeVTable<ZigZagVTable> for ZigZagVTable {
16    type Metadata = EmptyMetadata;
17
18    fn metadata(_array: &ZigZagArray) -> VortexResult<Option<Self::Metadata>> {
19        Ok(Some(EmptyMetadata))
20    }
21
22    fn build(
23        _encoding: &ZigZagEncoding,
24        dtype: &DType,
25        len: usize,
26        _metadata: &<Self::Metadata as DeserializeMetadata>::Output,
27        _buffers: &[ByteBuffer],
28        children: &dyn ArrayChildren,
29    ) -> VortexResult<ZigZagArray> {
30        if children.len() != 1 {
31            vortex_bail!("Expected 1 child, got {}", children.len());
32        }
33
34        let ptype = PType::try_from(dtype)?;
35        let encoded_type = DType::Primitive(ptype.to_unsigned(), dtype.nullability());
36
37        let encoded = children.get(0, &encoded_type, len)?;
38        ZigZagArray::try_new(encoded)
39    }
40}
41
42impl EncodeVTable<ZigZagVTable> for ZigZagVTable {
43    fn encode(
44        encoding: &ZigZagEncoding,
45        canonical: &Canonical,
46        _like: Option<&ZigZagArray>,
47    ) -> VortexResult<Option<ZigZagArray>> {
48        let parray = canonical.clone().into_primitive()?;
49
50        if !parray.ptype().is_signed_int() {
51            vortex_bail!(
52                "only signed integers can be encoded into {}, got {}",
53                encoding.id(),
54                parray.ptype()
55            )
56        }
57
58        Ok(Some(zigzag_encode(parray)?))
59    }
60}
61
62impl VisitorVTable<ZigZagVTable> for ZigZagVTable {
63    fn visit_buffers(_array: &ZigZagArray, _visitor: &mut dyn ArrayBufferVisitor) {}
64
65    fn visit_children(array: &ZigZagArray, visitor: &mut dyn ArrayChildVisitor) {
66        visitor.visit_child("encoded", array.encoded())
67    }
68}