vortex_array/arrays/piecewise_sequence/
mod.rs1use itertools::Itertools;
12use num_traits::AsPrimitive;
13use vortex_buffer::Buffer;
14use vortex_buffer::BufferMut;
15use vortex_error::VortexExpect;
16use vortex_error::VortexResult;
17use vortex_error::vortex_bail;
18use vortex_error::vortex_ensure;
19use vortex_error::vortex_ensure_eq;
20use vortex_error::vortex_err;
21
22use crate::ArrayRef;
23use crate::Columnar;
24use crate::IntoArray;
25use crate::array::ArrayView;
26use crate::arrays::ConstantArray;
27use crate::arrays::Primitive;
28use crate::arrays::PrimitiveArray;
29use crate::arrays::piecewise_sequence::array::PiecewiseSequenceArraySlotsExt;
30use crate::dtype::UnsignedPType;
31use crate::executor::ExecutionCtx;
32use crate::scalar::PValue;
33use crate::validity::Validity;
34
35pub mod array;
36mod vtable;
37
38#[cfg(test)]
39mod tests;
40
41pub use array::PiecewiseSequenceArrayExt;
42pub use vtable::*;
43
44pub(crate) fn check_index_arrays(
45 starts: &ArrayRef,
46 lengths: &ArrayRef,
47 multipliers: &ArrayRef,
48) -> VortexResult<()> {
49 check_index_array("starts", starts)?;
50 check_index_array("lengths", lengths)?;
51 check_index_array("multipliers", multipliers)?;
52 vortex_ensure_eq!(
53 starts.len(),
54 lengths.len(),
55 "PiecewiseSequenceArray starts length does not match lengths length",
56 );
57 vortex_ensure_eq!(
58 starts.len(),
59 multipliers.len(),
60 "PiecewiseSequenceArray starts length does not match multipliers length",
61 );
62 Ok(())
63}
64
65pub(crate) fn execute_index_arrays(
66 array: ArrayView<'_, PiecewiseSequence>,
67 ctx: &mut ExecutionCtx,
68) -> VortexResult<(PrimitiveArray, PrimitiveArray, PrimitiveArray)> {
69 let starts = array.starts().clone().execute::<PrimitiveArray>(ctx)?;
70 let lengths = array.lengths().clone().execute::<PrimitiveArray>(ctx)?;
71 let multipliers = array.multipliers().clone().execute::<PrimitiveArray>(ctx)?;
72 Ok((starts, lengths, multipliers))
73}
74
75pub(crate) fn maybe_contiguous_slices(
76 array: ArrayView<'_, PiecewiseSequence>,
77 ctx: &mut ExecutionCtx,
78) -> VortexResult<Option<(PrimitiveArray, Columnar)>> {
79 if !is_constant_one(array.multipliers()) {
80 return Ok(None);
81 }
82
83 let starts = array.starts().clone().execute::<PrimitiveArray>(ctx)?;
84 let lengths = array.lengths().clone().execute::<Columnar>(ctx)?;
85 Ok(Some((starts, lengths)))
86}
87
88pub(crate) fn is_constant_one(multipliers: &ArrayRef) -> bool {
89 let Some(scalar) = multipliers.as_constant() else {
90 return false;
91 };
92 matches!(
93 scalar.as_primitive_opt().and_then(|scalar| scalar.pvalue()),
94 Some(PValue::U8(1) | PValue::U16(1) | PValue::U32(1) | PValue::U64(1))
95 )
96}
97
98pub(crate) fn constant_unsigned_usize(array: &ConstantArray) -> usize {
99 let pvalue = array
100 .scalar()
101 .as_primitive_opt()
102 .and_then(|scalar| scalar.pvalue())
103 .vortex_expect("validated PiecewiseSequence length constants are primitive");
104
105 match pvalue {
106 PValue::U8(value) => value as usize,
107 PValue::U16(value) => value as usize,
108 PValue::U32(value) => value as usize,
109 PValue::U64(value) => value.as_(),
110 _ => unreachable!("validated PiecewiseSequence length constants are unsigned"),
111 }
112}
113
114fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> {
115 vortex_ensure!(
116 array.dtype().is_unsigned_int(),
117 "PiecewiseSequenceArray {name} must have unsigned integer dtype, got {}",
118 array.dtype()
119 );
120 vortex_ensure!(
121 !array.dtype().is_nullable(),
122 "PiecewiseSequenceArray {name} must be non-nullable, got {}",
123 array.dtype()
124 );
125 Ok(())
126}
127
128pub(crate) fn materialize_ranges<S, L, M>(
129 starts: ArrayView<'_, Primitive>,
130 lengths: ArrayView<'_, Primitive>,
131 multipliers: ArrayView<'_, Primitive>,
132 output_len: usize,
133) -> VortexResult<BufferMut<u64>>
134where
135 S: UnsignedPType,
136 L: UnsignedPType,
137 M: UnsignedPType,
138{
139 let starts = starts.as_slice::<S>();
140 let lengths = lengths.as_slice::<L>();
141 let multipliers = multipliers.as_slice::<M>();
142 let mut values = BufferMut::with_capacity(output_len);
143 let mut computed_len = 0usize;
144
145 for ((&start, &length), &multiplier) in starts.iter().zip_eq(lengths).zip_eq(multipliers) {
146 let start: usize = start.as_();
147 let length: usize = length.as_();
148 let multiplier: usize = multiplier.as_();
149 if length != 0 {
150 let last_offset = length - 1;
151 let last_delta = last_offset
152 .checked_mul(multiplier)
153 .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?;
154 start
155 .checked_add(last_delta)
156 .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?;
157 }
158 computed_len = computed_len
159 .checked_add(length)
160 .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?;
161
162 values.extend((0..length).map(|offset| (start + offset * multiplier) as u64));
163 }
164
165 if computed_len != output_len {
166 vortex_bail!(
167 "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}"
168 );
169 }
170 Ok(values)
171}
172
173pub(crate) fn contiguous_runs(starts: Vec<u64>, lengths: Vec<u64>, total: usize) -> ArrayRef {
176 let count = starts.len();
177 debug_assert_eq!(count, lengths.len());
178 let starts = PrimitiveArray::new(Buffer::from(starts), Validity::NonNullable).into_array();
179 let lengths = match lengths.first() {
180 Some(&first) if lengths.iter().all(|&length| length == first) => {
181 ConstantArray::new(first, count).into_array()
182 }
183 _ => PrimitiveArray::new(Buffer::from(lengths), Validity::NonNullable).into_array(),
184 };
185 let multipliers = ConstantArray::new(1u64, count).into_array();
186 unsafe { PiecewiseSequenceArray::new_unchecked(starts, lengths, multipliers, total) }
189 .into_array()
190}