Skip to main content

vortex_array/arrays/chunked/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::VortexResult;
7
8use crate::ArrayRef;
9use crate::ExecutionCtx;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::Chunked;
13use crate::arrays::ChunkedArray;
14use crate::arrays::chunked::ChunkedArrayExt;
15use crate::arrays::slice::SliceKernel;
16
17impl SliceKernel for Chunked {
18    fn slice(
19        array: ArrayView<'_, Self>,
20        range: Range<usize>,
21        _ctx: &mut ExecutionCtx,
22    ) -> VortexResult<Option<ArrayRef>> {
23        assert!(
24            !array.is_empty() || (range.start > 0 && range.end > 0),
25            "Empty chunked array can't be sliced from {} to {}",
26            range.start,
27            range.end
28        );
29
30        if array.is_empty() {
31            // SAFETY: empty chunked array trivially satisfies all validations
32            unsafe {
33                return Ok(Some(
34                    ChunkedArray::new_unchecked([], array.dtype().clone()).into_array(),
35                ));
36            }
37        }
38
39        let (offset_chunk, offset_in_first_chunk) = array.find_chunk_idx(range.start)?;
40        let (length_chunk, length_in_last_chunk) = array.find_chunk_idx(range.end)?;
41
42        if length_chunk == offset_chunk {
43            let chunk = array.chunk(offset_chunk);
44            return Ok(Some(
45                chunk.slice(offset_in_first_chunk..length_in_last_chunk)?,
46            ));
47        }
48
49        let first = array.chunk(offset_chunk);
50        let first = first.slice(offset_in_first_chunk..first.len())?;
51        let middle = (offset_chunk + 1..length_chunk).map(|i| array.chunk(i).clone());
52        let last = if length_in_last_chunk == 0 {
53            None
54        } else {
55            Some(array.chunk(length_chunk).slice(0..length_in_last_chunk)?)
56        };
57        let chunks = std::iter::once(first).chain(middle).chain(last);
58
59        // SAFETY: chunks are slices of the original valid chunks, preserving their dtype.
60        // All chunks maintain the same dtype as the original array.
61        Ok(Some(unsafe {
62            ChunkedArray::new_unchecked(chunks, array.dtype().clone()).into_array()
63        }))
64    }
65}