Skip to main content

vortex_array/arrays/dict/compute/
slice.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Range;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8
9use crate::ArrayRef;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::Constant;
13use crate::arrays::ConstantArray;
14use crate::arrays::Dict;
15use crate::arrays::DictArray;
16use crate::arrays::Primitive;
17use crate::arrays::dict::DictArraySlotsExt;
18use crate::arrays::slice::SliceReduce;
19use crate::scalar::Scalar;
20use crate::scalar::ScalarValue;
21use crate::stats::Precision;
22use crate::stats::Stat;
23
24impl SliceReduce for Dict {
25    fn slice(array: ArrayView<'_, Self>, range: Range<usize>) -> VortexResult<Option<ArrayRef>> {
26        if let Some(code) = array.codes().as_opt::<Constant>() {
27            return slice_constant_code(array, code.scalar(), range.len());
28        }
29
30        let sliced_code = if let Some(codes) = array.codes().as_typed::<Primitive>() {
31            let sliced_code = <Primitive as SliceReduce>::slice(codes, range)?
32                .vortex_expect("Primitive SliceReduce should always return Some");
33            // Because we specialize the primitive branch here, we have to make sure to handle the stat inheritance
34            inherit_selection_stats(array.codes(), &sliced_code);
35            sliced_code
36        } else {
37            array.codes().slice(range)?
38        };
39
40        // TODO(joe): if the range is size 1 replace with a constant array
41        // SAFETY: slicing the codes preserves invariants.
42        let array =
43            unsafe { DictArray::new_unchecked(sliced_code, array.values().clone()).into_array() };
44
45        Ok(Some(array))
46    }
47}
48
49/// Copies the stats of `source` that hold for any order-preserving selection of its rows, such as a
50/// slice or a filter.
51pub(super) fn inherit_selection_stats(source: &ArrayRef, selected: &ArrayRef) {
52    source.statistics().with_iter(|iter| {
53        selected
54            .statistics()
55            .inherit(iter.filter(|(stat, value)| is_inheritable_selection_stat(*stat, value)));
56    });
57}
58
59fn is_inheritable_selection_stat(stat: Stat, value: &Precision<ScalarValue>) -> bool {
60    matches!(
61        stat,
62        Stat::IsConstant | Stat::IsSorted | Stat::IsStrictSorted
63    ) && value
64        .as_ref()
65        .as_exact()
66        .is_some_and(|value| matches!(value, ScalarValue::Bool(true)))
67}
68
69pub(super) fn slice_constant_code(
70    array: ArrayView<'_, Dict>,
71    code: &Scalar,
72    len: usize,
73) -> VortexResult<Option<ArrayRef>> {
74    let code = code.as_primitive().as_::<usize>();
75    if let Some(code) = code {
76        let values = array.values().slice(code..code + 1)?;
77        // Keep the codes' nullability so the result's dtype matches the original dict's dtype.
78        let codes = ConstantArray::new(
79            Scalar::primitive(0u8, array.codes().dtype().nullability()),
80            len,
81        );
82        Ok(Some(
83            DictArray::new(codes.into_array(), values).into_array(),
84        ))
85    } else {
86        Ok(Some(
87            ConstantArray::new(Scalar::null(array.dtype().clone()), len).into_array(),
88        ))
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use std::sync::LazyLock;
95
96    use vortex_buffer::buffer;
97    use vortex_error::VortexResult;
98    use vortex_session::VortexSession;
99
100    use crate::IntoArray;
101    use crate::VortexSessionExecute;
102    use crate::arrays::DictArray;
103    use crate::arrays::PrimitiveArray;
104    use crate::arrays::dict::compute::slice::ConstantArray;
105    use crate::assert_arrays_eq;
106    use crate::dtype::DType;
107    use crate::dtype::Nullability::Nullable;
108    use crate::dtype::PType;
109    use crate::scalar::Scalar;
110
111    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
112
113    #[test]
114    fn slice_constant_valid_code() -> VortexResult<()> {
115        let mut ctx = SESSION.create_execution_ctx();
116        let dict = DictArray::new(
117            ConstantArray::new(1u8, 5).into_array(),
118            buffer![10i32, 20, 30].into_array(),
119        );
120        let sliced = dict.slice(1..4)?;
121        let expected = PrimitiveArray::from_iter([20i32, 20, 20]).into_array();
122        assert_arrays_eq!(sliced, expected, &mut ctx);
123        Ok(())
124    }
125
126    #[test]
127    fn slice_nullable_constant_valid_code() -> VortexResult<()> {
128        let mut ctx = SESSION.create_execution_ctx();
129        let dict = DictArray::new(
130            ConstantArray::new(Scalar::primitive(1u8, Nullable), 5).into_array(),
131            buffer![10i32, 20, 30].into_array(),
132        );
133        let sliced = dict.slice(1..4)?;
134        let expected = PrimitiveArray::from_option_iter([Some(20i32), Some(20), Some(20)]);
135        assert_arrays_eq!(sliced, expected.into_array(), &mut ctx);
136        Ok(())
137    }
138
139    #[test]
140    fn slice_constant_null_code() -> VortexResult<()> {
141        let mut ctx = SESSION.create_execution_ctx();
142        let dict = DictArray::new(
143            ConstantArray::new(Scalar::null(DType::Primitive(PType::U8, Nullable)), 5).into_array(),
144            buffer![10i32, 20, 30].into_array(),
145        );
146        let sliced = dict.slice(1..4)?;
147        let expected =
148            PrimitiveArray::from_option_iter([Option::<i32>::None, None, None]).into_array();
149        assert_arrays_eq!(sliced, expected, &mut ctx);
150        Ok(())
151    }
152}