Skip to main content

vortex_array/arrays/constant/vtable/
plugin.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! [`ArrayPlugin`] implementation for [`Constant`].
5
6use vortex_error::VortexResult;
7use vortex_error::vortex_ensure_eq;
8use vortex_session::VortexSession;
9
10use crate::Array;
11use crate::ArrayDeserialization;
12use crate::ArrayId;
13use crate::ArrayParts;
14use crate::ArrayPlugin;
15use crate::ArrayRef;
16use crate::ArraySerialization;
17use crate::ArraySlots;
18use crate::IntoArray;
19use crate::VTable;
20use crate::arrays::Constant;
21use crate::arrays::constant::ConstantData;
22use crate::scalar::Scalar;
23use crate::scalar::ScalarValue;
24
25impl ArrayPlugin for Constant {
26    fn id(&self) -> ArrayId {
27        VTable::id(self)
28    }
29
30    fn serialize(
31        &self,
32        array: &ArrayRef,
33        _session: &VortexSession,
34    ) -> VortexResult<Option<ArraySerialization>> {
35        vortex_ensure_eq!(
36            array.encoding_id(),
37            ArrayPlugin::id(self),
38            "Constant plugin cannot serialize an array of another encoding",
39        );
40        // HACK: Because the scalar is stored in the buffers, we do not need to serialize the
41        // metadata at all.
42        Ok(Some(ArraySerialization::from_array(
43            ArrayPlugin::id(self),
44            array,
45            vec![],
46        )))
47    }
48
49    fn deserialize(
50        &self,
51        parts: ArrayDeserialization<'_>,
52        session: &VortexSession,
53    ) -> VortexResult<ArrayRef> {
54        vortex_ensure_eq!(
55            parts.serialized_id,
56            ArrayPlugin::id(self),
57            "Constant plugin does not recognize the serialized ID",
58        );
59        let ArrayDeserialization {
60            dtype,
61            len,
62            buffers,
63            ..
64        } = parts;
65        vortex_ensure_eq!(buffers.len(), 1);
66
67        let buffer = buffers[0].clone().try_to_host_sync()?;
68        let bytes: &[u8] = buffer.as_ref();
69
70        let scalar_value = ScalarValue::from_proto_bytes(bytes, dtype, session)?;
71        let scalar = Scalar::try_new(dtype.clone(), scalar_value)?;
72
73        Ok(Array::try_from_parts(ArrayParts::new(
74            self.clone(),
75            dtype.clone(),
76            len,
77            ConstantData::new(scalar),
78            ArraySlots::new(),
79        ))?
80        .into_array())
81    }
82}