Skip to main content

vortex_array/arrays/patched/vtable/
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::IntoArray;
10use crate::array::ArrayView;
11use crate::arrays::Patched;
12use crate::arrays::patched::PatchedArrayExt;
13use crate::arrays::patched::PatchedArraySlotsExt;
14use crate::arrays::patched::PatchedSlots;
15use crate::arrays::slice::SliceReduce;
16
17impl SliceReduce for Patched {
18    fn slice(array: ArrayView<'_, Self>, range: Range<usize>) -> VortexResult<Option<ArrayRef>> {
19        // We **always** slice the patches at 1024-element chunk boundaries. We keep the offset + len
20        // around so that when we execute we know how much to chop off.
21        let new_offset = (range.start + array.offset()) % 1024;
22        let chunk_start = (range.start + array.offset()) / 1024;
23        let chunk_stop = (range.end + array.offset()).div_ceil(1024);
24        let sliced_lane_offsets = array
25            .lane_offsets()
26            .slice((chunk_start * array.n_lanes())..(chunk_stop * array.n_lanes()) + 1)?;
27
28        // Unlike the patches, we slice the inner to the exact range. This is handled
29        // at execution time by making sure to skip patch indices that are < offset
30        // or >= len.
31        let inner = array.inner().slice(range.start..range.end)?;
32        let len = inner.len();
33
34        let slots = PatchedSlots {
35            inner,
36            lane_offsets: sliced_lane_offsets,
37            patch_indices: array.patch_indices().clone(),
38            patch_values: array.patch_values().clone(),
39        }
40        .into_slots();
41
42        Ok(Some(
43            unsafe {
44                Patched::new_unchecked(
45                    array.dtype().clone(),
46                    len,
47                    slots,
48                    array.n_lanes(),
49                    new_offset,
50                )
51            }
52            .into_array(),
53        ))
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use std::ops::Range;
60    use std::sync::LazyLock;
61
62    use rstest::rstest;
63    use vortex_buffer::Buffer;
64    use vortex_buffer::BufferMut;
65    use vortex_buffer::buffer;
66    use vortex_error::VortexResult;
67    use vortex_session::VortexSession;
68
69    use crate::Canonical;
70    use crate::IntoArray;
71    use crate::VortexSessionExecute;
72    use crate::arrays::Patched;
73    use crate::arrays::PrimitiveArray;
74    use crate::assert_arrays_eq;
75    use crate::dtype::NativePType;
76    use crate::optimizer::ArrayOptimizer;
77    use crate::patches::Patches;
78
79    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
80
81    #[test]
82    fn test_reduce() -> VortexResult<()> {
83        let mut ctx = SESSION.create_execution_ctx();
84        let values = buffer![0u16; 512].into_array();
85        let patch_indices = buffer![1u32, 8, 30].into_array();
86        let patch_values = buffer![u16::MAX; 3].into_array();
87        let patches = Patches::new(512, 0, patch_indices, patch_values, None, &mut ctx)?;
88
89        let mut ctx = SESSION.create_execution_ctx();
90
91        let patched_array = Patched::from_array_and_patches(values, &patches, &mut ctx)?;
92
93        let sliced = patched_array
94            .into_array()
95            .slice(1..10)?
96            .optimize_ctx(&SESSION)?;
97
98        insta::assert_snapshot!(
99            sliced.display_tree_encodings_only(),
100            @r#"
101            root: vortex.patched(u16, len=9)
102              inner: vortex.primitive(u16, len=9)
103              lane_offsets: vortex.primitive(u32, len=33)
104              patch_indices: vortex.primitive(u16, len=3)
105              patch_values: vortex.primitive(u16, len=3)
106            "#);
107
108        let executed = sliced.execute::<Canonical>(&mut ctx)?.into_primitive();
109
110        assert_eq!(
111            &[u16::MAX, 0, 0, 0, 0, 0, 0, u16::MAX, 0],
112            executed.as_slice::<u16>()
113        );
114
115        Ok(())
116    }
117
118    #[rstest]
119    #[case::trivial(buffer![1u64; 2], buffer![1u32], buffer![u64::MAX], 1..2)]
120    #[case::one_chunk(buffer![0u64; 1024], buffer![1u32, 8, 30], buffer![u64::MAX; 3], 1..10)]
121    #[case::multichunk(buffer![1u64; 10_000], buffer![0u32, 1, 2, 3, 4, 16, 17, 18, 19, 1024, 2048, 2049], buffer![u64::MAX; 12], 1024..5000)]
122    fn test_cases<T: NativePType>(
123        #[case] inner: Buffer<T>,
124        #[case] patch_indices: Buffer<u32>,
125        #[case] patch_values: Buffer<T>,
126        #[case] range: Range<usize>,
127    ) {
128        let mut expected = inner.to_vec();
129        for (&index, &value) in patch_indices.iter().zip(patch_values.iter()) {
130            expected[index as usize] = value;
131        }
132        let expected = PrimitiveArray::from_iter(expected[range.clone()].iter().copied());
133
134        // Create patched array.
135        let patches = Patches::new(
136            inner.len(),
137            0,
138            patch_indices.into_array(),
139            patch_values.into_array(),
140            None,
141            &mut SESSION.create_execution_ctx(),
142        )
143        .unwrap();
144
145        let mut ctx = SESSION.create_execution_ctx();
146
147        let patched_array = Patched::from_array_and_patches(inner.into_array(), &patches, &mut ctx)
148            .unwrap()
149            .into_array();
150
151        let slice_first = patched_array.slice(range).unwrap();
152
153        assert_arrays_eq!(slice_first, &expected, &mut ctx);
154    }
155
156    #[test]
157    fn test_stacked_slices() {
158        let mut ctx = SESSION.create_execution_ctx();
159        let values = PrimitiveArray::from_iter(0u64..10_000).into_array();
160
161        let patched_indices = buffer![1u32, 2, 1024, 2048, 3072, 3088].into_array();
162        let patched_values = buffer![0u64, 1, 2, 3, 4, 5].into_array();
163
164        let patches =
165            Patches::new(10_000, 0, patched_indices, patched_values, None, &mut ctx).unwrap();
166
167        let patched_array = Patched::from_array_and_patches(values, &patches, &mut ctx)
168            .unwrap()
169            .into_array();
170
171        let sliced = patched_array
172            .slice(1024..5000)
173            .unwrap()
174            .slice(1..2065)
175            .unwrap();
176
177        let mut expected = BufferMut::from_iter(1025u64..=3088);
178        expected[1023] = 3;
179        expected[2047] = 4;
180        expected[2063] = 5;
181
182        let expected = expected.into_array();
183
184        assert_arrays_eq!(sliced, expected, &mut ctx);
185    }
186}