Skip to main content

vortex_array/arrays/repeated/
rules.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Range;
5
6use vortex_error::VortexResult;
7use vortex_session::VortexSession;
8
9use crate::ArrayRef;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::ChunkedArray;
13use crate::arrays::Repeated;
14use crate::arrays::RepeatedArray;
15use crate::arrays::Slice;
16use crate::arrays::repeated::RepeatedArraySlotsExt;
17use crate::arrays::slice::SliceReduce;
18use crate::arrays::slice::SliceReduceAdaptor;
19use crate::optimizer::kernels::ArrayKernelsExt;
20
21pub(super) fn register_parent_rules(session: &VortexSession) {
22    session.kernels().register_reduce_parent_rule(
23        Slice,
24        Repeated,
25        const { &SliceReduceAdaptor(Repeated) },
26    );
27}
28
29impl SliceReduce for Repeated {
30    fn slice(array: ArrayView<'_, Self>, range: Range<usize>) -> VortexResult<Option<ArrayRef>> {
31        // The range is non-empty, so the child is too.
32        let child = array.child();
33        let child_len = child.len();
34        let rotation = range.start % child_len;
35
36        // A range inside one copy is a slice of the child.
37        if rotation + range.len() <= child_len {
38            return Ok(Some(child.slice(rotation..rotation + range.len())?));
39        }
40
41        // Any other range repeats the child rotated to start where the range does.
42        let rotated = if rotation == 0 {
43            child.clone()
44        } else {
45            ChunkedArray::try_new(
46                [child.slice(rotation..child_len)?, child.slice(0..rotation)?],
47                child.dtype().clone(),
48            )?
49            .into_array()
50        };
51        Ok(Some(
52            RepeatedArray::try_new(rotated, range.len())?.into_array(),
53        ))
54    }
55}