Skip to main content

vortex_array/arrays/slice/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Reduce and execute adaptors for slice operations.
5//!
6//! Encodings that know how to slice themselves implement [`SliceReduce`] (metadata-only)
7//! or [`SliceKernel`] (buffer-reading). The adaptors [`SliceReduceAdaptor`] and
8//! [`SliceExecuteAdaptor`] bridge these into the execution model as
9//! [`ArrayParentReduceRule`] and [`ExecuteParentKernel`] respectively.
10
11mod array;
12mod rules;
13mod slice_;
14mod take;
15mod vtable;
16
17use std::ops::Range;
18
19pub use array::SliceArraySlotsExt;
20pub use array::SliceData;
21pub use array::SliceDataParts;
22pub use array::SliceSlots;
23pub use array::SliceSlotsView;
24use vortex_error::VortexResult;
25pub use vtable::*;
26
27use crate::ArrayRef;
28use crate::Canonical;
29use crate::ExecutionCtx;
30use crate::IntoArray;
31use crate::array::ArrayView;
32use crate::array::VTable;
33use crate::kernel::ExecuteParentKernel;
34use crate::matcher::Matcher;
35use crate::optimizer::rules::ArrayParentReduceRule;
36
37pub(crate) fn initialize(session: &vortex_session::VortexSession) {
38    rules::register_parent_rules(session);
39}
40
41pub trait SliceReduce: VTable {
42    /// Slice an array with the provided range without reading buffers.
43    ///
44    /// This trait is for slice implementations that can operate purely on array metadata and
45    /// structure without needing to read or execute on the underlying buffers. Implementations
46    /// should return `None` if slicing requires buffer access.
47    ///
48    /// # Preconditions
49    ///
50    /// The range is guaranteed to be within bounds of the array (i.e., `range.end <= array.len()`).
51    ///
52    /// Additionally, the range is guaranteed to be non-empty (i.e., `range.start < range.end`).
53    fn slice(array: ArrayView<'_, Self>, range: Range<usize>) -> VortexResult<Option<ArrayRef>>;
54}
55
56pub trait SliceKernel: VTable {
57    /// Slice an array with the provided range, potentially reading buffers.
58    ///
59    /// Unlike [`SliceReduce`], this trait is for slice implementations that may need to read
60    /// and execute on the underlying buffers to produce the sliced result.
61    ///
62    /// # Preconditions
63    ///
64    /// The range is guaranteed to be within bounds of the array (i.e., `range.end <= array.len()`).
65    ///
66    /// Additionally, the range is guaranteed to be non-empty (i.e., `range.start < range.end`).
67    fn slice(
68        array: ArrayView<'_, Self>,
69        range: Range<usize>,
70        ctx: &mut ExecutionCtx,
71    ) -> VortexResult<Option<ArrayRef>>;
72}
73
74/// Short-circuits slice for the ranges that need no encoding-specific work.
75///
76/// Returns `Some(result)` when the answer is already known, or `None` when the slice must proceed
77/// normally.
78fn short_circuit<V: VTable>(array: ArrayView<'_, V>, range: &Range<usize>) -> Option<ArrayRef> {
79    if range.start == 0 && range.end == array.len() {
80        return Some(array.array().clone());
81    }
82    if range.start == range.end {
83        return Some(Canonical::empty(array.dtype()).into_array());
84    }
85    None
86}
87
88/// Adaptor that wraps a [`SliceReduce`] impl as an [`ArrayParentReduceRule`].
89#[derive(Default, Debug)]
90pub struct SliceReduceAdaptor<V>(pub V);
91
92impl<V> ArrayParentReduceRule<V> for SliceReduceAdaptor<V>
93where
94    V: SliceReduce,
95{
96    type Parent = Slice;
97
98    fn reduce_parent(
99        &self,
100        array: ArrayView<'_, V>,
101        parent: <Self::Parent as Matcher>::Match<'_>,
102        child_idx: usize,
103    ) -> VortexResult<Option<ArrayRef>> {
104        assert_eq!(child_idx, 0);
105        if let Some(result) = short_circuit::<V>(array, &parent.range) {
106            return Ok(Some(result));
107        }
108        <V as SliceReduce>::slice(array, parent.range.clone())
109    }
110}
111
112/// Adaptor that wraps a [`SliceKernel`] impl as an [`ExecuteParentKernel`].
113#[derive(Default, Debug)]
114pub struct SliceExecuteAdaptor<V>(pub V);
115
116impl<V> ExecuteParentKernel<V> for SliceExecuteAdaptor<V>
117where
118    V: SliceKernel,
119{
120    type Parent = Slice;
121
122    fn execute_parent(
123        &self,
124        array: ArrayView<'_, V>,
125        parent: <Self::Parent as Matcher>::Match<'_>,
126        child_idx: usize,
127        ctx: &mut ExecutionCtx,
128    ) -> VortexResult<Option<ArrayRef>> {
129        assert_eq!(child_idx, 0);
130        if let Some(result) = short_circuit::<V>(array, &parent.range) {
131            return Ok(Some(result));
132        }
133        <V as SliceKernel>::slice(array, parent.range.clone(), ctx)
134    }
135}