Skip to main content

vortex_array/arrays/repeated/
vtable.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::iter;
5
6use vortex_error::VortexResult;
7use vortex_error::vortex_ensure;
8use vortex_error::vortex_ensure_eq;
9use vortex_error::vortex_err;
10use vortex_error::vortex_panic;
11use vortex_session::registry::CachedId;
12
13use crate::AnyCanonical;
14use crate::ArrayRef;
15use crate::Canonical;
16use crate::EmptyArrayData;
17use crate::ExecutionCtx;
18use crate::ExecutionResult;
19use crate::IntoArray;
20use crate::array::Array;
21use crate::array::ArrayId;
22use crate::array::ArrayParts;
23use crate::array::ArrayView;
24use crate::array::OperationsVTable;
25use crate::array::ProbeState;
26use crate::array::VTable;
27use crate::array::ValidityVTable;
28use crate::array::with_empty_buffers;
29use crate::arrays::ChunkedArray;
30use crate::arrays::Constant;
31use crate::arrays::ConstantArray;
32use crate::arrays::ExtensionArray;
33use crate::arrays::FixedSizeListArray;
34use crate::arrays::ListViewArray;
35use crate::arrays::StructArray;
36use crate::arrays::VariantArray;
37use crate::arrays::extension::ExtensionArrayExt;
38use crate::arrays::fixed_size_list::FixedSizeListArrayExt;
39use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
40use crate::arrays::listview::ListViewArrayExt;
41use crate::arrays::listview::ListViewArraySlotsExt;
42use crate::arrays::repeated::RepeatedArraySlotsExt;
43use crate::arrays::repeated::RepeatedSlots;
44use crate::arrays::struct_::StructArrayExt;
45use crate::arrays::variant::VariantArraySlotsExt;
46use crate::buffer::BufferHandle;
47use crate::builders::ArrayBuilder;
48use crate::dtype::DType;
49use crate::require_child;
50use crate::scalar::Scalar;
51use crate::validity::Validity;
52
53/// The encoding of a [`RepeatedArray`].
54#[derive(Clone, Debug)]
55pub struct Repeated;
56
57/// A [`Repeated`]-encoded array, which repeats its child end to end.
58pub type RepeatedArray = Array<Repeated>;
59
60impl VTable for Repeated {
61    type TypedArrayData = EmptyArrayData;
62
63    type OperationsVTable = Self;
64    type ValidityVTable = Self;
65
66    fn id(&self) -> ArrayId {
67        static ID: CachedId = CachedId::new("vortex.repeated");
68        *ID
69    }
70
71    fn validate(
72        &self,
73        _data: &EmptyArrayData,
74        dtype: &DType,
75        len: usize,
76        slots: &[Option<ArrayRef>],
77    ) -> VortexResult<()> {
78        vortex_ensure_eq!(slots.len(), RepeatedSlots::COUNT);
79        let child = slots[RepeatedSlots::CHILD]
80            .as_ref()
81            .ok_or_else(|| vortex_err!("Repeated requires a child"))?;
82        vortex_ensure_eq!(
83            child.dtype(),
84            dtype,
85            "Repeated child dtype does not match outer dtype"
86        );
87        vortex_ensure!(
88            len == 0 || !child.is_empty(),
89            "Repeated cannot repeat an empty child to {len} rows"
90        );
91        Ok(())
92    }
93
94    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
95        0
96    }
97
98    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
99        vortex_panic!("Repeated buffer index {idx} out of bounds")
100    }
101
102    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
103        None
104    }
105
106    fn with_buffers(
107        &self,
108        array: ArrayView<'_, Self>,
109        buffers: &[BufferHandle],
110    ) -> VortexResult<ArrayParts<Self>> {
111        with_empty_buffers(self, array, buffers)
112    }
113
114    fn append_to_builder(
115        array: ArrayView<'_, Self>,
116        builder: &mut dyn ArrayBuilder,
117        ctx: &mut ExecutionCtx,
118    ) -> VortexResult<()> {
119        if array.is_empty() {
120            return Ok(());
121        }
122        let child = array.child().clone().execute::<Canonical>(ctx)?;
123        // A nested child appends its children repeated, which a builder keeps as one chunk each.
124        if let Some(repeated) = repeat_nested(child.clone(), array.len())? {
125            return repeated.append_to_builder(builder, ctx);
126        }
127        let child = child.into_array();
128        for copy in copies(&child, array.len())? {
129            copy.append_to_builder(builder, ctx)?;
130        }
131        Ok(())
132    }
133
134    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
135        RepeatedSlots::NAMES[idx].to_string()
136    }
137
138    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
139        if array.is_empty() {
140            return Ok(ExecutionResult::done(
141                Canonical::empty(array.dtype()).into_array(),
142            ));
143        }
144        if array.child().len() == 1 {
145            let scalar = array.child().execute_scalar(0, ctx)?;
146            return Ok(ExecutionResult::done(
147                ConstantArray::new(scalar, array.len()).into_array(),
148            ));
149        }
150
151        let array = require_child!(array, array.child(), RepeatedSlots::CHILD => AnyCanonical);
152
153        let child = Canonical::from(array.child().as_::<AnyCanonical>());
154        if let Some(repeated) = repeat_nested(child, array.len())? {
155            return Ok(ExecutionResult::done(repeated));
156        }
157
158        // Decode the child once, then let `Chunked` append the decoded child once per copy.
159        let chunked =
160            ChunkedArray::try_new(copies(array.child(), array.len())?, array.dtype().clone())?;
161        Ok(ExecutionResult::done(chunked.into_array()))
162    }
163
164    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
165        if array.is_empty() {
166            return Ok(Some(Canonical::empty(array.dtype()).into_array()));
167        }
168        let child = array.child();
169        if array.len() <= child.len() {
170            return Ok(Some(child.slice(0..array.len())?));
171        }
172        if let Some(constant) = child.as_opt::<Constant>() {
173            return Ok(Some(
174                ConstantArray::new(constant.scalar().clone(), array.len()).into_array(),
175            ));
176        }
177        // An inner repeat that ends on a whole copy of its own child repeats that child exactly.
178        if let Some(inner) = child.as_opt::<Repeated>()
179            && inner.len().is_multiple_of(inner.child().len())
180        {
181            return Ok(Some(
182                RepeatedArray::try_new(inner.child().clone(), array.len())?.into_array(),
183            ));
184        }
185        Ok(None)
186    }
187}
188
189/// Repeats a nested canonical `child` to `len` rows by repeating its children, without copying
190/// any values.
191///
192/// A canonical array is canonical at the top level only, so the result keeps its children as
193/// `Repeated` arrays. Returns `None` for a child whose values are its own buffers, which must be
194/// copied.
195fn repeat_nested(child: Canonical, len: usize) -> VortexResult<Option<ArrayRef>> {
196    let repeat = |array: &ArrayRef| -> VortexResult<ArrayRef> {
197        Ok(RepeatedArray::try_new(array.clone(), len)?.into_array())
198    };
199    Ok(Some(match child {
200        Canonical::Struct(array) => StructArray::try_new(
201            array.names().clone(),
202            array
203                .iter_unmasked_fields()
204                .map(repeat)
205                .collect::<VortexResult<Vec<_>>>()?,
206            len,
207            repeat_validity(array.struct_validity(), len)?,
208        )?
209        .into_array(),
210        Canonical::FixedSizeList(array) => {
211            let list_size = array.list_size();
212            let elements_len = len
213                .checked_mul(list_size as usize)
214                .ok_or_else(|| vortex_err!("{len} lists of {list_size} elements overflow usize"))?;
215            FixedSizeListArray::try_new(
216                RepeatedArray::try_new(array.elements().clone(), elements_len)?.into_array(),
217                list_size,
218                repeat_validity(array.fixed_size_list_validity(), len)?,
219                len,
220            )?
221            .into_array()
222        }
223        Canonical::List(array) => {
224            // SAFETY: every view of the result is a view of `array` over the same elements, so the
225            // offsets and sizes keep their types and stay within the elements.
226            unsafe {
227                ListViewArray::new_unchecked(
228                    array.elements().clone(),
229                    repeat(array.offsets())?,
230                    repeat(array.sizes())?,
231                    repeat_validity(array.listview_validity(), len)?,
232                )
233            }
234            .into_array()
235        }
236        Canonical::Extension(array) => {
237            ExtensionArray::try_new(array.ext_dtype().clone(), repeat(array.storage_array())?)?
238                .into_array()
239        }
240        Canonical::Variant(array) => VariantArray::try_new(
241            repeat(array.core_storage())?,
242            array.shredded().map(repeat).transpose()?,
243        )?
244        .into_array(),
245        _ => return Ok(None),
246    }))
247}
248
249/// Repeats `validity` to `len` rows.
250fn repeat_validity(validity: Validity, len: usize) -> VortexResult<Validity> {
251    Ok(match validity {
252        Validity::Array(validity) => {
253            Validity::Array(RepeatedArray::try_new(validity, len)?.into_array())
254        }
255        validity => validity,
256    })
257}
258
259/// Returns the copies of the non-empty `child` that make up `len` rows: whole copies of `child`,
260/// then a prefix of it for the last, partial copy.
261fn copies(child: &ArrayRef, len: usize) -> VortexResult<impl Iterator<Item = ArrayRef>> {
262    let whole = len / child.len();
263    let rest = len % child.len();
264    let partial = (rest > 0).then(|| child.slice(0..rest)).transpose()?;
265    Ok(iter::repeat_n(child.clone(), whole).chain(partial))
266}
267
268impl OperationsVTable<Repeated> for Repeated {
269    type ProbeState = ();
270
271    fn probe_scalar(
272        state: &mut ProbeState<'_, Repeated>,
273        index: usize,
274        ctx: &mut ExecutionCtx,
275    ) -> VortexResult<Scalar> {
276        let child_index = index % state.array().child().len();
277        state
278            .slot(RepeatedSlots::CHILD)?
279            .ok_or_else(|| vortex_err!("Repeated child slot is missing"))?
280            .execute_scalar(child_index, ctx)
281    }
282
283    fn scalar_at(
284        array: ArrayView<'_, Repeated>,
285        index: usize,
286        ctx: &mut ExecutionCtx,
287    ) -> VortexResult<Scalar> {
288        Self::probe_scalar(&mut ProbeState::once(array), index, ctx)
289    }
290}
291
292impl ValidityVTable<Repeated> for Repeated {
293    fn validity(array: ArrayView<'_, Repeated>) -> VortexResult<Validity> {
294        repeat_validity(array.child().validity()?, array.len())
295    }
296}