Skip to main content

vortex_zigzag/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::hash::Hasher;
7
8use vortex_array::Array;
9use vortex_array::ArrayEq;
10use vortex_array::ArrayHash;
11use vortex_array::ArrayId;
12use vortex_array::ArrayParts;
13use vortex_array::ArrayRef;
14use vortex_array::ArrayView;
15use vortex_array::ExecutionCtx;
16use vortex_array::ExecutionResult;
17use vortex_array::IntoArray;
18use vortex_array::Precision;
19use vortex_array::TypedArrayRef;
20use vortex_array::buffer::BufferHandle;
21use vortex_array::dtype::DType;
22use vortex_array::dtype::PType;
23use vortex_array::match_each_unsigned_integer_ptype;
24use vortex_array::scalar::Scalar;
25use vortex_array::serde::ArrayChildren;
26use vortex_array::vtable::OperationsVTable;
27use vortex_array::vtable::VTable;
28use vortex_array::vtable::ValidityChild;
29use vortex_array::vtable::ValidityVTableFromChild;
30use vortex_error::VortexExpect;
31use vortex_error::VortexResult;
32use vortex_error::vortex_bail;
33use vortex_error::vortex_ensure;
34use vortex_error::vortex_panic;
35use vortex_session::VortexSession;
36use zigzag::ZigZag as ExternalZigZag;
37
38use crate::compute::ZigZagEncoded;
39use crate::kernel::PARENT_KERNELS;
40use crate::rules::RULES;
41use crate::zigzag_decode;
42
43/// A [`ZigZag`]-encoded Vortex array.
44pub type ZigZagArray = Array<ZigZag>;
45
46impl VTable for ZigZag {
47    type ArrayData = ZigZagData;
48
49    type OperationsVTable = Self;
50    type ValidityVTable = ValidityVTableFromChild;
51
52    fn id(&self) -> ArrayId {
53        Self::ID
54    }
55
56    fn validate(
57        &self,
58        _data: &Self::ArrayData,
59        dtype: &DType,
60        len: usize,
61        slots: &[Option<ArrayRef>],
62    ) -> VortexResult<()> {
63        let encoded = slots[ENCODED_SLOT]
64            .as_ref()
65            .vortex_expect("ZigZagArray encoded slot");
66        let expected_dtype = ZigZagData::dtype_from_encoded_dtype(encoded.dtype())?;
67        vortex_ensure!(
68            dtype == &expected_dtype,
69            "expected dtype {expected_dtype}, got {dtype}"
70        );
71        vortex_ensure!(
72            encoded.len() == len,
73            "expected len {len}, got {}",
74            encoded.len()
75        );
76        Ok(())
77    }
78
79    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
80        0
81    }
82
83    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
84        vortex_panic!("ZigZagArray buffer index {idx} out of bounds")
85    }
86
87    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
88        vortex_panic!("ZigZagArray buffer_name index {idx} out of bounds")
89    }
90
91    fn serialize(
92        _array: ArrayView<'_, Self>,
93        _session: &VortexSession,
94    ) -> VortexResult<Option<Vec<u8>>> {
95        Ok(Some(vec![]))
96    }
97
98    fn deserialize(
99        &self,
100        dtype: &DType,
101        len: usize,
102        metadata: &[u8],
103        _buffers: &[BufferHandle],
104        children: &dyn ArrayChildren,
105        _session: &VortexSession,
106    ) -> VortexResult<ArrayParts<Self>> {
107        if !metadata.is_empty() {
108            vortex_bail!(
109                "ZigZagArray expects empty metadata, got {} bytes",
110                metadata.len()
111            );
112        }
113        if children.len() != 1 {
114            vortex_bail!("Expected 1 child, got {}", children.len());
115        }
116
117        let ptype = PType::try_from(dtype)?;
118        let encoded_type = DType::Primitive(ptype.to_unsigned(), dtype.nullability());
119
120        let encoded = children.get(0, &encoded_type, len)?;
121        let slots = vec![Some(encoded.clone())];
122        let data = ZigZagData::try_new(encoded.dtype())?;
123        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
124    }
125
126    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
127        SLOT_NAMES[idx].to_string()
128    }
129
130    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
131        Ok(ExecutionResult::done(
132            zigzag_decode(array.encoded().clone().execute(ctx)?).into_array(),
133        ))
134    }
135
136    fn reduce_parent(
137        array: ArrayView<'_, Self>,
138        parent: &ArrayRef,
139        child_idx: usize,
140    ) -> VortexResult<Option<ArrayRef>> {
141        RULES.evaluate(array, parent, child_idx)
142    }
143
144    fn execute_parent(
145        array: ArrayView<'_, Self>,
146        parent: &ArrayRef,
147        child_idx: usize,
148        ctx: &mut ExecutionCtx,
149    ) -> VortexResult<Option<ArrayRef>> {
150        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
151    }
152}
153
154impl ArrayHash for ZigZagData {
155    fn array_hash<H: Hasher>(&self, _state: &mut H, _precision: Precision) {}
156}
157
158impl ArrayEq for ZigZagData {
159    fn array_eq(&self, _other: &Self, _precision: Precision) -> bool {
160        true
161    }
162}
163
164/// The zigzag-encoded values (signed integers mapped to unsigned).
165pub(super) const ENCODED_SLOT: usize = 0;
166pub(super) const NUM_SLOTS: usize = 1;
167pub(super) const SLOT_NAMES: [&str; NUM_SLOTS] = ["encoded"];
168
169#[derive(Clone, Debug)]
170pub struct ZigZagData {}
171
172impl Display for ZigZagData {
173    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
174        Ok(())
175    }
176}
177
178pub trait ZigZagArrayExt: TypedArrayRef<ZigZag> {
179    fn encoded(&self) -> &ArrayRef {
180        self.as_ref().slots()[ENCODED_SLOT]
181            .as_ref()
182            .vortex_expect("ZigZagArray encoded slot")
183    }
184
185    fn ptype(&self) -> PType {
186        PType::try_from(self.encoded().dtype())
187            .vortex_expect("ZigZagArray encoded dtype")
188            .to_signed()
189    }
190}
191
192impl<T: TypedArrayRef<ZigZag>> ZigZagArrayExt for T {}
193
194#[derive(Clone, Debug)]
195pub struct ZigZag;
196
197impl ZigZag {
198    pub const ID: ArrayId = ArrayId::new_ref("vortex.zigzag");
199
200    /// Construct a new [`ZigZagArray`] from an encoded unsigned integer array.
201    pub fn try_new(encoded: ArrayRef) -> VortexResult<ZigZagArray> {
202        let dtype = ZigZagData::dtype_from_encoded_dtype(encoded.dtype())?;
203        let len = encoded.len();
204        let slots = vec![Some(encoded.clone())];
205        let data = ZigZagData::try_new(encoded.dtype())?;
206        Ok(unsafe {
207            Array::from_parts_unchecked(ArrayParts::new(ZigZag, dtype, len, data).with_slots(slots))
208        })
209    }
210}
211
212impl ZigZagData {
213    fn dtype_from_encoded_dtype(encoded_dtype: &DType) -> VortexResult<DType> {
214        Ok(DType::from(PType::try_from(encoded_dtype)?.to_signed())
215            .with_nullability(encoded_dtype.nullability()))
216    }
217
218    pub fn new() -> Self {
219        Self {}
220    }
221
222    pub fn try_new(encoded_dtype: &DType) -> VortexResult<Self> {
223        if !encoded_dtype.is_unsigned_int() {
224            vortex_bail!(MismatchedTypes: "unsigned int", encoded_dtype);
225        }
226
227        Self::dtype_from_encoded_dtype(encoded_dtype)?;
228
229        Ok(Self {})
230    }
231}
232
233impl Default for ZigZagData {
234    fn default() -> Self {
235        Self::new()
236    }
237}
238
239impl OperationsVTable<ZigZag> for ZigZag {
240    fn scalar_at(
241        array: ArrayView<'_, ZigZag>,
242        index: usize,
243        _ctx: &mut ExecutionCtx,
244    ) -> VortexResult<Scalar> {
245        let scalar = array.encoded().scalar_at(index)?;
246        if scalar.is_null() {
247            return scalar.primitive_reinterpret_cast(ZigZagArrayExt::ptype(&array));
248        }
249
250        let pscalar = scalar.as_primitive();
251        Ok(match_each_unsigned_integer_ptype!(pscalar.ptype(), |P| {
252            Scalar::primitive(
253                <<P as ZigZagEncoded>::Int>::decode(
254                    pscalar
255                        .typed_value::<P>()
256                        .vortex_expect("zigzag corruption"),
257                ),
258                array.dtype().nullability(),
259            )
260        }))
261    }
262}
263
264impl ValidityChild<ZigZag> for ZigZag {
265    fn validity_child(array: ArrayView<'_, ZigZag>) -> ArrayRef {
266        array.encoded().clone()
267    }
268}
269
270#[cfg(test)]
271mod test {
272    use vortex_array::IntoArray;
273    use vortex_array::ToCanonical;
274    use vortex_array::scalar::Scalar;
275    use vortex_buffer::buffer;
276
277    use super::*;
278    use crate::zigzag_encode;
279
280    #[test]
281    fn test_compute_statistics() -> VortexResult<()> {
282        let array = buffer![1i32, -5i32, 2, 3, 4, 5, 6, 7, 8, 9, 10]
283            .into_array()
284            .to_primitive();
285        let zigzag = zigzag_encode(array.clone())?;
286
287        assert_eq!(
288            zigzag.statistics().compute_max::<i32>(),
289            array.statistics().compute_max::<i32>()
290        );
291        assert_eq!(
292            zigzag.statistics().compute_null_count(),
293            array.statistics().compute_null_count()
294        );
295        assert_eq!(
296            zigzag.statistics().compute_is_constant(),
297            array.statistics().compute_is_constant()
298        );
299
300        let sliced = zigzag.slice(0..2).unwrap();
301        let sliced = sliced.as_::<ZigZag>();
302        assert_eq!(
303            sliced.array().scalar_at(sliced.len() - 1).unwrap(),
304            Scalar::from(-5i32)
305        );
306
307        assert_eq!(
308            sliced.statistics().compute_min::<i32>(),
309            array.statistics().compute_min::<i32>()
310        );
311        assert_eq!(
312            sliced.statistics().compute_null_count(),
313            array.statistics().compute_null_count()
314        );
315        assert_eq!(
316            sliced.statistics().compute_is_constant(),
317            array.statistics().compute_is_constant()
318        );
319        Ok(())
320    }
321}