Skip to main content

vortex_runend/
compress.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::Itertools;
5use vortex_array::ArrayRef;
6use vortex_array::IntoArray;
7use vortex_array::ToCanonical;
8use vortex_array::arrays::BoolArray;
9use vortex_array::arrays::ConstantArray;
10use vortex_array::arrays::PrimitiveArray;
11use vortex_array::arrays::VarBinViewArray;
12use vortex_array::buffer::BufferHandle;
13use vortex_array::dtype::NativePType;
14use vortex_array::dtype::Nullability;
15use vortex_array::expr::stats::Precision;
16use vortex_array::expr::stats::Stat;
17use vortex_array::match_each_native_ptype;
18use vortex_array::match_each_unsigned_integer_ptype;
19use vortex_array::scalar::Scalar;
20use vortex_array::validity::Validity;
21use vortex_array::vtable::ValidityHelper;
22use vortex_buffer::BitBuffer;
23use vortex_buffer::BitBufferMut;
24use vortex_buffer::Buffer;
25use vortex_buffer::BufferMut;
26use vortex_buffer::buffer;
27use vortex_error::VortexExpect;
28use vortex_error::VortexResult;
29use vortex_mask::Mask;
30
31use crate::iter::trimmed_ends_iter;
32
33/// Run-end encode a `PrimitiveArray`, returning a tuple of `(ends, values)`.
34pub fn runend_encode(array: &PrimitiveArray) -> (PrimitiveArray, ArrayRef) {
35    let validity = match array.validity() {
36        Validity::NonNullable => None,
37        Validity::AllValid => None,
38        Validity::AllInvalid => {
39            // We can trivially return an all-null REE array
40            let ends = PrimitiveArray::new(buffer![array.len() as u64], Validity::NonNullable);
41            ends.statistics()
42                .set(Stat::IsStrictSorted, Precision::Exact(true.into()));
43            return (
44                ends,
45                ConstantArray::new(Scalar::null(array.dtype().clone()), 1).into_array(),
46            );
47        }
48        Validity::Array(a) => Some(a.to_bool().to_bit_buffer()),
49    };
50
51    let (ends, values) = match validity {
52        None => {
53            match_each_native_ptype!(array.ptype(), |P| {
54                let (ends, values) = runend_encode_primitive(array.as_slice::<P>());
55                (
56                    PrimitiveArray::new(ends, Validity::NonNullable),
57                    PrimitiveArray::new(values, array.dtype().nullability().into()).into_array(),
58                )
59            })
60        }
61        Some(validity) => {
62            match_each_native_ptype!(array.ptype(), |P| {
63                let (ends, values) =
64                    runend_encode_nullable_primitive(array.as_slice::<P>(), validity);
65                (
66                    PrimitiveArray::new(ends, Validity::NonNullable),
67                    values.into_array(),
68                )
69            })
70        }
71    };
72
73    let ends = ends
74        .narrow()
75        .vortex_expect("Ends must succeed downcasting")
76        .to_primitive();
77
78    ends.statistics()
79        .set(Stat::IsStrictSorted, Precision::Exact(true.into()));
80
81    (ends, values)
82}
83
84fn runend_encode_primitive<T: NativePType>(elements: &[T]) -> (Buffer<u64>, Buffer<T>) {
85    let mut ends = BufferMut::empty();
86    let mut values = BufferMut::empty();
87
88    if elements.is_empty() {
89        return (ends.freeze(), values.freeze());
90    }
91
92    // Run-end encode the values
93    let mut prev = elements[0];
94    let mut end = 1;
95    for &e in elements.iter().skip(1) {
96        if e != prev {
97            ends.push(end);
98            values.push(prev);
99        }
100        prev = e;
101        end += 1;
102    }
103    ends.push(end);
104    values.push(prev);
105
106    (ends.freeze(), values.freeze())
107}
108
109fn runend_encode_nullable_primitive<T: NativePType>(
110    elements: &[T],
111    element_validity: BitBuffer,
112) -> (Buffer<u64>, PrimitiveArray) {
113    let mut ends = BufferMut::empty();
114    let mut values = BufferMut::empty();
115    let mut validity = BitBufferMut::with_capacity(values.capacity());
116
117    if elements.is_empty() {
118        return (
119            ends.freeze(),
120            PrimitiveArray::new(
121                values,
122                Validity::Array(BoolArray::from(validity.freeze()).into_array()),
123            ),
124        );
125    }
126
127    // Run-end encode the values
128    let mut prev = element_validity.value(0).then(|| elements[0]);
129    let mut end = 1;
130    for e in elements
131        .iter()
132        .zip(element_validity.iter())
133        .map(|(&e, is_valid)| is_valid.then_some(e))
134        .skip(1)
135    {
136        if e != prev {
137            ends.push(end);
138            match prev {
139                None => {
140                    validity.append(false);
141                    values.push(T::default());
142                }
143                Some(p) => {
144                    validity.append(true);
145                    values.push(p);
146                }
147            }
148        }
149        prev = e;
150        end += 1;
151    }
152    ends.push(end);
153
154    match prev {
155        None => {
156            validity.append(false);
157            values.push(T::default());
158        }
159        Some(p) => {
160            validity.append(true);
161            values.push(p);
162        }
163    }
164
165    (
166        ends.freeze(),
167        PrimitiveArray::new(values, Validity::from(validity.freeze())),
168    )
169}
170
171pub fn runend_decode_primitive(
172    ends: PrimitiveArray,
173    values: PrimitiveArray,
174    offset: usize,
175    length: usize,
176) -> VortexResult<PrimitiveArray> {
177    let validity_mask = values.validity_mask()?;
178    Ok(match_each_native_ptype!(values.ptype(), |P| {
179        match_each_unsigned_integer_ptype!(ends.ptype(), |E| {
180            runend_decode_typed_primitive(
181                trimmed_ends_iter(ends.as_slice::<E>(), offset, length),
182                values.as_slice::<P>(),
183                validity_mask,
184                values.dtype().nullability(),
185                length,
186            )
187        })
188    }))
189}
190
191/// Decode a run-end encoded slice of values into a flat `Buffer<T>` and `Validity`.
192///
193/// This is the core decode loop shared by primitive and varbinview run-end decoding.
194fn runend_decode_slice<T: Copy + Default>(
195    run_ends: impl Iterator<Item = usize>,
196    values: &[T],
197    values_validity: Mask,
198    values_nullability: Nullability,
199    length: usize,
200) -> (Buffer<T>, Validity) {
201    match values_validity {
202        Mask::AllTrue(_) => {
203            let mut decoded: BufferMut<T> = BufferMut::with_capacity(length);
204            for (end, value) in run_ends.zip_eq(values) {
205                assert!(
206                    end >= decoded.len(),
207                    "Runend ends must be monotonic, got {end} after {}",
208                    decoded.len()
209                );
210                assert!(end <= length, "Runend end must be less than overall length");
211                // SAFETY:
212                // We preallocate enough capacity because we know the total length
213                unsafe { decoded.push_n_unchecked(*value, end - decoded.len()) };
214            }
215            (decoded.into(), values_nullability.into())
216        }
217        Mask::AllFalse(_) => (Buffer::<T>::zeroed(length), Validity::AllInvalid),
218        Mask::Values(mask) => {
219            let mut decoded = BufferMut::with_capacity(length);
220            let mut decoded_validity = BitBufferMut::with_capacity(length);
221            for (end, value) in run_ends.zip_eq(
222                values
223                    .iter()
224                    .zip(mask.bit_buffer().iter())
225                    .map(|(&v, is_valid)| is_valid.then_some(v)),
226            ) {
227                assert!(
228                    end >= decoded.len(),
229                    "Runend ends must be monotonic, got {end} after {}",
230                    decoded.len()
231                );
232                assert!(end <= length, "Runend end must be less than overall length");
233                match value {
234                    None => {
235                        decoded_validity.append_n(false, end - decoded.len());
236                        // SAFETY:
237                        // We preallocate enough capacity because we know the total length
238                        unsafe { decoded.push_n_unchecked(T::default(), end - decoded.len()) };
239                    }
240                    Some(value) => {
241                        decoded_validity.append_n(true, end - decoded.len());
242                        // SAFETY:
243                        // We preallocate enough capacity because we know the total length
244                        unsafe { decoded.push_n_unchecked(value, end - decoded.len()) };
245                    }
246                }
247            }
248            (decoded.into(), Validity::from(decoded_validity.freeze()))
249        }
250    }
251}
252
253pub fn runend_decode_typed_primitive<T: NativePType>(
254    run_ends: impl Iterator<Item = usize>,
255    values: &[T],
256    values_validity: Mask,
257    values_nullability: Nullability,
258    length: usize,
259) -> PrimitiveArray {
260    let (decoded, validity) = runend_decode_slice(
261        run_ends,
262        values,
263        values_validity,
264        values_nullability,
265        length,
266    );
267    PrimitiveArray::new(decoded, validity)
268}
269
270/// Decode a run-end encoded VarBinView array by expanding views directly.
271pub fn runend_decode_varbinview(
272    ends: PrimitiveArray,
273    values: VarBinViewArray,
274    offset: usize,
275    length: usize,
276) -> VortexResult<VarBinViewArray> {
277    let validity_mask = values.validity_mask()?;
278    let views = values.views();
279
280    let (decoded_views, validity) = match_each_unsigned_integer_ptype!(ends.ptype(), |E| {
281        runend_decode_slice(
282            trimmed_ends_iter(ends.as_slice::<E>(), offset, length),
283            views,
284            validity_mask,
285            values.dtype().nullability(),
286            length,
287        )
288    });
289
290    let parts = values.into_parts();
291    let view_handle = BufferHandle::new_host(decoded_views.into_byte_buffer());
292
293    // SAFETY: we are expanding views from a valid VarBinViewArray with the same
294    // buffers, so all buffer indices and offsets remain valid.
295    Ok(unsafe {
296        VarBinViewArray::new_handle_unchecked(view_handle, parts.buffers, parts.dtype, validity)
297    })
298}
299
300#[cfg(test)]
301mod test {
302    use vortex_array::ToCanonical;
303    use vortex_array::arrays::PrimitiveArray;
304    use vortex_array::assert_arrays_eq;
305    use vortex_array::validity::Validity;
306    use vortex_buffer::BitBuffer;
307    use vortex_buffer::buffer;
308    use vortex_error::VortexResult;
309
310    use crate::compress::runend_decode_primitive;
311    use crate::compress::runend_encode;
312
313    #[test]
314    fn encode() {
315        let arr = PrimitiveArray::from_iter([1i32, 1, 2, 2, 2, 3, 3, 3, 3, 3]);
316        let (ends, values) = runend_encode(&arr);
317        let values = values.to_primitive();
318
319        let expected_ends = PrimitiveArray::from_iter(vec![2u8, 5, 10]);
320        assert_arrays_eq!(ends, expected_ends);
321        let expected_values = PrimitiveArray::from_iter(vec![1i32, 2, 3]);
322        assert_arrays_eq!(values, expected_values);
323    }
324
325    #[test]
326    fn encode_nullable() {
327        let arr = PrimitiveArray::new(
328            buffer![1i32, 1, 2, 2, 2, 3, 3, 3, 3, 3],
329            Validity::from(BitBuffer::from(vec![
330                true, true, false, false, true, true, true, true, false, false,
331            ])),
332        );
333        let (ends, values) = runend_encode(&arr);
334        let values = values.to_primitive();
335
336        let expected_ends = PrimitiveArray::from_iter(vec![2u8, 4, 5, 8, 10]);
337        assert_arrays_eq!(ends, expected_ends);
338        let expected_values =
339            PrimitiveArray::from_option_iter(vec![Some(1i32), None, Some(2), Some(3), None]);
340        assert_arrays_eq!(values, expected_values);
341    }
342
343    #[test]
344    fn encode_all_null() {
345        let arr = PrimitiveArray::new(
346            buffer![0, 0, 0, 0, 0],
347            Validity::from(BitBuffer::new_unset(5)),
348        );
349        let (ends, values) = runend_encode(&arr);
350        let values = values.to_primitive();
351
352        let expected_ends = PrimitiveArray::from_iter(vec![5u64]);
353        assert_arrays_eq!(ends, expected_ends);
354        let expected_values = PrimitiveArray::from_option_iter(vec![Option::<i32>::None]);
355        assert_arrays_eq!(values, expected_values);
356    }
357
358    #[test]
359    fn decode() -> VortexResult<()> {
360        let ends = PrimitiveArray::from_iter([2u32, 5, 10]);
361        let values = PrimitiveArray::from_iter([1i32, 2, 3]);
362        let decoded = runend_decode_primitive(ends, values, 0, 10)?;
363
364        let expected = PrimitiveArray::from_iter(vec![1i32, 1, 2, 2, 2, 3, 3, 3, 3, 3]);
365        assert_arrays_eq!(decoded, expected);
366        Ok(())
367    }
368}