Skip to main content

vortex_array/arrays/runend/
ops.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;
7
8use crate::ArrayRef;
9use crate::ArrayView;
10use crate::ExecutionCtx;
11use crate::ProbeState;
12use crate::arrays::runend::RunEnd;
13use crate::match_each_unsigned_integer_ptype;
14use crate::scalar::Scalar;
15use crate::search_sorted::SearchResult;
16use crate::search_sorted::SearchSorted;
17use crate::search_sorted::SearchSortedPrimitiveArray;
18use crate::search_sorted::SearchSortedSide;
19use crate::vtable::OperationsVTable;
20
21impl OperationsVTable<RunEnd> for RunEnd {
22    type ProbeState = super::probe::RunEndProbeState;
23
24    fn probe_scalar(
25        state: &mut ProbeState<'_, RunEnd>,
26        index: usize,
27        ctx: &mut ExecutionCtx,
28    ) -> VortexResult<Scalar> {
29        super::probe::scalar_at(state, index, ctx)
30    }
31
32    fn scalar_at(
33        array: ArrayView<'_, RunEnd>,
34        index: usize,
35        ctx: &mut ExecutionCtx,
36    ) -> VortexResult<Scalar> {
37        super::probe::scalar_at(&mut ProbeState::once(array), index, ctx)
38    }
39}
40
41/// Find the physical offset for and index that would be an end of the slice i.e., one past the last element.
42///
43/// If the index exists in the array we want to take that position (as we are searching from the right)
44/// otherwise we want to take the next one
45pub fn find_slice_end_index(
46    array: &ArrayRef,
47    index: usize,
48    ctx: &mut ExecutionCtx,
49) -> VortexResult<usize> {
50    let result = match_each_unsigned_integer_ptype!(array.dtype().as_ptype(), |T| {
51        SearchSortedPrimitiveArray::<T>::new(array, ctx)
52            .search_sorted(&index, SearchSortedSide::Right)?
53    });
54    Ok(slice_end_index(result, array.len()))
55}
56
57/// Find the physical index (the run) that contains the logical `index`, given the run `ends`.
58pub fn find_physical_index(
59    array: &ArrayRef,
60    index: usize,
61    ctx: &mut ExecutionCtx,
62) -> VortexResult<usize> {
63    match_each_unsigned_integer_ptype!(array.dtype().as_ptype(), |T| {
64        Ok(SearchSortedPrimitiveArray::<T>::new(array, ctx)
65            .search_sorted(&index, SearchSortedSide::Right)?
66            .to_ends_index(array.len()))
67    })
68}
69
70/// Find the physical range of runs covering the logical `range`, given the run `ends`.
71///
72/// Equivalent to [`find_physical_index`] of the start and [`find_slice_end_index`] of the end,
73/// but both searches share one searcher, and so one probe of `ends`.
74pub fn find_physical_range(
75    array: &ArrayRef,
76    range: Range<usize>,
77    ctx: &mut ExecutionCtx,
78) -> VortexResult<Range<usize>> {
79    match_each_unsigned_integer_ptype!(array.dtype().as_ptype(), |T| {
80        let searcher = SearchSortedPrimitiveArray::<T>::new(array, ctx);
81        let start = searcher
82            .search_sorted(&range.start, SearchSortedSide::Right)?
83            .to_ends_index(array.len());
84        let end = slice_end_index(
85            searcher.search_sorted(&range.end, SearchSortedSide::Right)?,
86            array.len(),
87        );
88        Ok(start..end)
89    })
90}
91
92fn slice_end_index(result: SearchResult, len: usize) -> usize {
93    match result {
94        SearchResult::Found(i) => i,
95        SearchResult::NotFound(i) => {
96            if i == len {
97                i
98            } else {
99                i + 1
100            }
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use std::sync::LazyLock;
108
109    use vortex_buffer::buffer;
110    use vortex_session::VortexSession;
111
112    use crate::IntoArray;
113    use crate::VortexSessionExecute;
114    use crate::aggregate_fn::fns::is_constant::is_constant;
115    use crate::arrays::PrimitiveArray;
116    use crate::arrays::runend::RunEnd;
117    use crate::assert_arrays_eq;
118    use crate::dtype::DType;
119    use crate::dtype::Nullability;
120    use crate::dtype::PType;
121
122    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
123
124    #[test]
125    fn slice_array() {
126        let mut ctx = SESSION.create_execution_ctx();
127        let arr = RunEnd::try_new(
128            buffer![2u32, 5, 10].into_array(),
129            buffer![1i32, 2, 3].into_array(),
130            &mut ctx,
131        )
132        .unwrap()
133        .slice(3..8)
134        .unwrap();
135        assert_eq!(
136            arr.dtype(),
137            &DType::Primitive(PType::I32, Nullability::NonNullable)
138        );
139        assert_eq!(arr.len(), 5);
140
141        let expected = PrimitiveArray::from_iter(vec![2i32, 2, 3, 3, 3]).into_array();
142        assert_arrays_eq!(arr, expected, &mut ctx);
143    }
144
145    #[test]
146    fn double_slice() {
147        let mut ctx = SESSION.create_execution_ctx();
148        let arr = RunEnd::try_new(
149            buffer![2u32, 5, 10].into_array(),
150            buffer![1i32, 2, 3].into_array(),
151            &mut ctx,
152        )
153        .unwrap()
154        .slice(3..8)
155        .unwrap();
156        assert_eq!(arr.len(), 5);
157
158        let doubly_sliced = arr.slice(0..3).unwrap();
159
160        let expected = PrimitiveArray::from_iter(vec![2i32, 2, 3]).into_array();
161        assert_arrays_eq!(doubly_sliced, expected, &mut ctx);
162    }
163
164    #[test]
165    fn slice_end_inclusive() {
166        let mut ctx = SESSION.create_execution_ctx();
167        let arr = RunEnd::try_new(
168            buffer![2u32, 5, 10].into_array(),
169            buffer![1i32, 2, 3].into_array(),
170            &mut ctx,
171        )
172        .unwrap()
173        .slice(4..10)
174        .unwrap();
175        assert_eq!(
176            arr.dtype(),
177            &DType::Primitive(PType::I32, Nullability::NonNullable)
178        );
179        assert_eq!(arr.len(), 6);
180
181        let expected = PrimitiveArray::from_iter(vec![2i32, 3, 3, 3, 3, 3]).into_array();
182        assert_arrays_eq!(arr, expected, &mut ctx);
183    }
184
185    #[test]
186    fn slice_at_end() {
187        let mut ctx = SESSION.create_execution_ctx();
188        let re_array = RunEnd::try_new(
189            buffer![7_u64, 10].into_array(),
190            buffer![2_u64, 3].into_array(),
191            &mut ctx,
192        )
193        .unwrap();
194
195        assert_eq!(re_array.len(), 10);
196
197        let sliced_array = re_array.slice(re_array.len()..re_array.len()).unwrap();
198        assert!(sliced_array.is_empty());
199    }
200
201    #[test]
202    fn slice_single_end() {
203        let mut ctx = SESSION.create_execution_ctx();
204        let re_array = RunEnd::try_new(
205            buffer![7_u64, 10].into_array(),
206            buffer![2_u64, 3].into_array(),
207            &mut ctx,
208        )
209        .unwrap();
210
211        assert_eq!(re_array.len(), 10);
212
213        let sliced_array = re_array.slice(2..5).unwrap();
214
215        assert!(is_constant(&sliced_array, &mut ctx).unwrap());
216        assert_arrays_eq!(
217            sliced_array,
218            PrimitiveArray::from_iter([2u64, 2, 2]),
219            &mut ctx
220        );
221    }
222
223    #[test]
224    fn ree_scalar_at_end() {
225        let mut ctx = SESSION.create_execution_ctx();
226        let scalar = RunEnd::encode(
227            buffer![1, 1, 1, 4, 4, 4, 2, 2, 5, 5, 5, 5].into_array(),
228            &mut ctx,
229        )
230        .unwrap()
231        .execute_scalar(11, &mut ctx)
232        .unwrap();
233        assert_eq!(scalar, 5.into());
234    }
235
236    #[test]
237    fn slice_along_run_boundaries() {
238        let mut ctx = SESSION.create_execution_ctx();
239        // Create a runend array with runs: [1, 1, 1] [4, 4, 4] [2, 2] [5, 5, 5, 5]
240        // Run ends at indices: 3, 6, 8, 12
241        let arr = RunEnd::try_new(
242            buffer![3u32, 6, 8, 12].into_array(),
243            buffer![1i32, 4, 2, 5].into_array(),
244            &mut ctx,
245        )
246        .unwrap();
247
248        // Slice from start of first run to end of first run (indices 0..3)
249        let slice1 = arr.slice(0..3).unwrap();
250        assert_eq!(slice1.len(), 3);
251        let expected = PrimitiveArray::from_iter(vec![1i32, 1, 1]).into_array();
252        assert_arrays_eq!(slice1, expected, &mut ctx);
253
254        // Slice from start of second run to end of second run (indices 3..6)
255        let slice2 = arr.slice(3..6).unwrap();
256        assert_eq!(slice2.len(), 3);
257        let expected = PrimitiveArray::from_iter(vec![4i32, 4, 4]).into_array();
258        assert_arrays_eq!(slice2, expected, &mut ctx);
259
260        // Slice from start of third run to end of third run (indices 6..8)
261        let slice3 = arr.slice(6..8).unwrap();
262        assert_eq!(slice3.len(), 2);
263        let expected = PrimitiveArray::from_iter(vec![2i32, 2]).into_array();
264        assert_arrays_eq!(slice3, expected, &mut ctx);
265
266        // Slice from start of last run to end of last run (indices 8..12)
267        let slice4 = arr.slice(8..12).unwrap();
268        assert_eq!(slice4.len(), 4);
269        let expected = PrimitiveArray::from_iter(vec![5i32, 5, 5, 5]).into_array();
270        assert_arrays_eq!(slice4, expected, &mut ctx);
271
272        // Slice spanning exactly two runs (indices 3..8)
273        let slice5 = arr.slice(3..8).unwrap();
274        assert_eq!(slice5.len(), 5);
275        let expected = PrimitiveArray::from_iter(vec![4i32, 4, 4, 2, 2]).into_array();
276        assert_arrays_eq!(slice5, expected, &mut ctx);
277
278        // Slice from middle of first run to end of second run (indices 1..6)
279        let slice6 = arr.slice(1..6).unwrap();
280        assert_eq!(slice6.len(), 5);
281        let expected = PrimitiveArray::from_iter(vec![1i32, 1, 4, 4, 4]).into_array();
282        assert_arrays_eq!(slice6, expected, &mut ctx);
283
284        // Slice from start of second run to middle of third run (indices 3..7)
285        let slice7 = arr.slice(3..7).unwrap();
286        assert_eq!(slice7.len(), 4);
287        let expected = PrimitiveArray::from_iter(vec![4i32, 4, 4, 2]).into_array();
288        assert_arrays_eq!(slice7, expected, &mut ctx);
289    }
290}