Skip to main content

arrow_select/coalesce/
primitive.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::coalesce::{InProgressArray, append_gathered_nulls, check_filter_len};
6use crate::filter::{FilterIndices, FilterPredicate, FilterSelection, FilterSlices};
7use arrow_array::cast::AsArray;
8use arrow_array::{Array, ArrayRef, ArrowPrimitiveType, PrimitiveArray, UInt32Array};
9use arrow_buffer::{NullBuffer, NullBufferBuilder, ScalarBuffer};
10use arrow_schema::{ArrowError, DataType};
11use std::fmt::Debug;
12use std::sync::Arc;
13
14/// InProgressArray for [`PrimitiveArray`]
15#[derive(Debug)]
16pub(crate) struct InProgressPrimitiveArray<T: ArrowPrimitiveType> {
17    /// Data type of the array
18    data_type: DataType,
19    /// The current source, if any
20    source: Option<ArrayRef>,
21    /// the target batch size (and thus size for views allocation)
22    batch_size: usize,
23    /// In progress nulls
24    nulls: NullBufferBuilder,
25    /// The currently in progress array
26    current: Vec<T::Native>,
27}
28
29impl<T: ArrowPrimitiveType> InProgressPrimitiveArray<T> {
30    /// Create a new `InProgressPrimitiveArray`
31    pub(crate) fn new(batch_size: usize, data_type: DataType) -> Self {
32        Self {
33            data_type,
34            batch_size,
35            source: None,
36            nulls: NullBufferBuilder::new(batch_size),
37            current: vec![],
38        }
39    }
40
41    /// Allocate space for output values if necessary.
42    ///
43    /// This is done on write (when we know it is necessary) rather than
44    /// eagerly to avoid allocations that are not used.
45    fn ensure_capacity(&mut self) {
46        if self.current.capacity() == 0 {
47            self.current.reserve(self.batch_size);
48        }
49    }
50
51    /// # Safety
52    ///
53    /// Every index yielded by `indices` must be less than `values.len()`, and
54    /// `indices` must yield exactly `selected_count` indices.
55    unsafe fn append_values_by_indices(
56        current: &mut Vec<T::Native>,
57        values: &[T::Native],
58        indices: FilterIndices<'_>,
59        selected_count: usize,
60    ) {
61        current.reserve(selected_count);
62        let current_len = current.len();
63        let mut written = 0;
64
65        // SAFETY: the caller guarantees that indices are in bounds and that
66        // exactly `selected_count` values are written. Capacity was reserved
67        // above.
68        unsafe {
69            let mut out = current
70                .spare_capacity_mut()
71                .as_mut_ptr()
72                .cast::<T::Native>();
73
74            indices.for_each(|idx| {
75                out.write(*values.get_unchecked(idx));
76                out = out.add(1);
77                written += 1;
78            });
79
80            current.set_len(current_len + written);
81        }
82
83        debug_assert_eq!(written, selected_count);
84    }
85
86    /// # Safety
87    ///
88    /// Every range yielded by `slices` must satisfy
89    /// `start <= end <= values.len()`, and the ranges must contain exactly
90    /// `selected_count` values in total.
91    unsafe fn append_values_by_slices(
92        current: &mut Vec<T::Native>,
93        values: &[T::Native],
94        slices: FilterSlices<'_>,
95        selected_count: usize,
96    ) {
97        current.reserve(selected_count);
98        let current_len = current.len();
99        let mut written = 0;
100
101        // SAFETY: the caller guarantees that slices are in bounds and that
102        // exactly `selected_count` values are written. Capacity was reserved
103        // above.
104        unsafe {
105            let mut out = current
106                .spare_capacity_mut()
107                .as_mut_ptr()
108                .cast::<T::Native>();
109
110            slices.for_each(|(start, end)| {
111                let len = end - start;
112                std::ptr::copy_nonoverlapping(values.as_ptr().add(start), out, len);
113                out = out.add(len);
114                written += len;
115            });
116
117            current.set_len(current_len + written);
118        }
119
120        debug_assert_eq!(written, selected_count);
121    }
122}
123
124#[inline]
125fn primitive_source<T: ArrowPrimitiveType>(
126    source: Option<&ArrayRef>,
127) -> Result<&PrimitiveArray<T>, ArrowError> {
128    Ok(source
129        .ok_or_else(|| {
130            ArrowError::InvalidArgumentError(
131                "Internal Error: InProgressPrimitiveArray: source not set".to_string(),
132            )
133        })?
134        .as_primitive::<T>())
135}
136
137fn append_filtered_nulls(
138    nulls: &mut NullBufferBuilder,
139    source_nulls: Option<&NullBuffer>,
140    filter: &FilterPredicate,
141) {
142    if let Some(filtered_nulls) = filter.filter_nulls(source_nulls) {
143        nulls.append_buffer(&filtered_nulls);
144    } else {
145        nulls.append_n_non_nulls(filter.count());
146    }
147}
148
149impl<T: ArrowPrimitiveType + Debug> InProgressArray for InProgressPrimitiveArray<T> {
150    fn supports_dense_indexed_copy(&self) -> bool {
151        true
152    }
153
154    fn set_source(&mut self, source: Option<ArrayRef>) {
155        self.source = source;
156    }
157
158    fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), ArrowError> {
159        self.ensure_capacity();
160
161        let s = primitive_source::<T>(self.source.as_ref())?;
162
163        // add nulls if necessary
164        if let Some(nulls) = s.nulls().as_ref() {
165            let nulls = nulls.slice(offset, len);
166            self.nulls.append_buffer(&nulls);
167        } else {
168            self.nulls.append_n_non_nulls(len);
169        }
170
171        // Copy the values
172        let values = s.values();
173        self.current
174            .extend_from_slice(&values[offset..offset + len]);
175
176        Ok(())
177    }
178
179    fn copy_rows_by_filter(&mut self, filter: &FilterPredicate) -> Result<(), ArrowError> {
180        let source_len = primitive_source::<T>(self.source.as_ref())?.len();
181        check_filter_len(filter, source_len)?;
182
183        match filter.selection() {
184            FilterSelection::Indices(indices) => {
185                self.ensure_capacity();
186                let s = primitive_source::<T>(self.source.as_ref())?;
187
188                append_filtered_nulls(&mut self.nulls, s.nulls(), filter);
189                // SAFETY: `check_filter_len` verified the selected indices are
190                // in bounds, and the filter yields `filter.count()` indices.
191                unsafe {
192                    Self::append_values_by_indices(
193                        &mut self.current,
194                        s.values(),
195                        indices,
196                        filter.count(),
197                    )
198                };
199                Ok(())
200            }
201            FilterSelection::Slices(slices) => {
202                self.ensure_capacity();
203                let s = primitive_source::<T>(self.source.as_ref())?;
204
205                append_filtered_nulls(&mut self.nulls, s.nulls(), filter);
206                // SAFETY: `check_filter_len` verified the selected slices are
207                // in bounds, and the filter yields `filter.count()` values.
208                unsafe {
209                    Self::append_values_by_slices(
210                        &mut self.current,
211                        s.values(),
212                        slices,
213                        filter.count(),
214                    )
215                };
216                Ok(())
217            }
218            // Other selection shapes reuse the generic copy_rows path.
219            selection => self.copy_rows_by_selection(selection),
220        }
221    }
222
223    /// # Safety
224    ///
225    /// `indices` must not contain nulls, and every value must be less than
226    /// `source.len()`.
227    unsafe fn copy_rows_by_indices(
228        &mut self,
229        source: &ArrayRef,
230        indices: &UInt32Array,
231    ) -> Result<(), ArrowError> {
232        if indices.is_empty() {
233            return Ok(());
234        }
235        let typed = source.as_primitive::<T>();
236        self.ensure_capacity();
237
238        if let Some(src_nulls) = typed.nulls() {
239            // SAFETY: the caller validated every index against `typed.len()`, which
240            // equals the length of its null buffer.
241            unsafe { append_gathered_nulls(&mut self.nulls, src_nulls, indices) };
242        } else {
243            self.nulls.append_n_non_nulls(indices.len());
244        }
245
246        let index_values = indices.values();
247        let values = typed.values();
248        let current_len = self.current.len();
249        self.current.reserve(indices.len());
250        debug_assert!(
251            index_values
252                .iter()
253                .all(|&idx| (idx as usize) < values.len()),
254            "copy_rows_by_indices requires caller-validated in-bounds indices",
255        );
256        // SAFETY: the caller guarantees every index is in bounds, and reserve
257        // allocated one output slot per index.
258        unsafe {
259            let base = self
260                .current
261                .spare_capacity_mut()
262                .as_mut_ptr()
263                .cast::<T::Native>();
264            let src = values.as_ptr();
265            for (i, &idx) in index_values.iter().enumerate() {
266                base.add(i).write(*src.add(idx as usize));
267            }
268            self.current.set_len(current_len + indices.len());
269        }
270        Ok(())
271    }
272
273    fn finish(&mut self) -> Result<ArrayRef, ArrowError> {
274        // take and reset the current values and nulls
275        let values = std::mem::take(&mut self.current);
276        let nulls = self.nulls.finish();
277        self.nulls = NullBufferBuilder::new(self.batch_size);
278
279        let array = PrimitiveArray::<T>::try_new(ScalarBuffer::from(values), nulls)?
280            // preserve timezone / precision+scale if applicable
281            .with_data_type(self.data_type.clone());
282        Ok(Arc::new(array))
283    }
284
285    fn size(&self) -> usize {
286        self.source
287            .as_ref()
288            .map_or(0, |source| source.get_array_memory_size())
289            + self.current.capacity() * std::mem::size_of::<T::Native>()
290            + self.nulls.allocated_size()
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use crate::filter::FilterBuilder;
298    use crate::take::take;
299    use arrow_array::types::Int32Type;
300    use arrow_array::{BooleanArray, Int32Array, UInt32Array};
301
302    #[test]
303    fn test_copy_rows_by_filter_index_iterator() {
304        let source =
305            Int32Array::from_iter((0..21).map(|idx| if idx % 5 == 0 { None } else { Some(idx) }));
306        let filter = BooleanArray::from_iter(
307            (0..21).map(|idx| Some(matches!(idx, 0 | 1 | 2 | 3 | 5 | 8 | 13))),
308        );
309        let predicate = FilterBuilder::new(&filter).build();
310        let FilterSelection::Indices(indices) = predicate.selection() else {
311            panic!("expected index iterator selection");
312        };
313        let mut selected_indices = Vec::new();
314        indices.for_each(|idx| selected_indices.push(idx));
315        assert_eq!(selected_indices, vec![0, 1, 2, 3, 5, 8, 13]);
316
317        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(7, DataType::Int32);
318        in_progress.set_source(Some(Arc::new(source)));
319        in_progress.copy_rows_by_filter(&predicate).unwrap();
320
321        let result = in_progress.finish().unwrap();
322        let result = result.as_primitive::<Int32Type>();
323        let expected = Int32Array::from(vec![
324            None,
325            Some(1),
326            Some(2),
327            Some(3),
328            None,
329            Some(8),
330            Some(13),
331        ]);
332        assert_eq!(result, &expected);
333    }
334
335    #[test]
336    fn test_copy_rows_by_filter_slice_iterator() {
337        let source =
338            Int32Array::from_iter((0..16).map(|idx| if idx % 5 == 0 { None } else { Some(idx) }));
339        let filter = BooleanArray::from_iter((0..16).map(|idx| Some(!matches!(idx, 3 | 9))));
340        let predicate = FilterBuilder::new(&filter).build();
341        let FilterSelection::Slices(slices) = predicate.selection() else {
342            panic!("expected slice iterator selection");
343        };
344        let mut selected_slices = Vec::new();
345        slices.for_each(|slice| selected_slices.push(slice));
346        assert_eq!(selected_slices, vec![(0, 3), (4, 9), (10, 16)]);
347
348        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(14, DataType::Int32);
349        in_progress.set_source(Some(Arc::new(source)));
350        in_progress.copy_rows_by_filter(&predicate).unwrap();
351
352        let result = in_progress.finish().unwrap();
353        let result = result.as_primitive::<Int32Type>();
354        let expected = Int32Array::from(vec![
355            None,
356            Some(1),
357            Some(2),
358            Some(4),
359            None,
360            Some(6),
361            Some(7),
362            Some(8),
363            None,
364            Some(11),
365            Some(12),
366            Some(13),
367            Some(14),
368            None,
369        ]);
370        assert_eq!(result, &expected);
371    }
372
373    #[test]
374    fn test_copy_rows_by_filter_rejects_all_filter_longer_than_source() {
375        let source: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
376        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(4, DataType::Int32);
377        in_progress.set_source(Some(source));
378
379        let filter = BooleanArray::from(vec![true; 4]);
380        let predicate = FilterBuilder::new(&filter).build();
381        assert!(matches!(predicate.selection(), FilterSelection::All { .. }));
382
383        let err = in_progress.copy_rows_by_filter(&predicate).unwrap_err();
384        assert!(matches!(
385            err,
386            ArrowError::InvalidArgumentError(message)
387                if message == "Filter predicate of length 4 is larger than source array of length 3"
388        ));
389    }
390
391    #[test]
392    fn test_size_empty() {
393        // A fresh in-progress array has allocated nothing yet
394        let in_progress = InProgressPrimitiveArray::<Int32Type>::new(64, DataType::Int32);
395        assert_eq!(in_progress.size(), 0);
396    }
397
398    #[test]
399    fn test_size_counts_source() {
400        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(64, DataType::Int32);
401        let source: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
402        in_progress.set_source(Some(Arc::clone(&source)));
403        // Nothing copied yet, so size is exactly the source's memory
404        assert_eq!(in_progress.size(), source.get_array_memory_size());
405    }
406
407    #[test]
408    fn test_size_counts_values_buffer_and_resets_on_finish() {
409        const BATCH_SIZE: usize = 64;
410        let mut in_progress =
411            InProgressPrimitiveArray::<Int32Type>::new(BATCH_SIZE, DataType::Int32);
412        // Non-null source: the nulls builder stays empty (allocated_size == 0),
413        // so the only growth is the values buffer.
414        let source: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
415        let source_size = source.get_array_memory_size();
416        in_progress.set_source(Some(Arc::clone(&source)));
417
418        in_progress.copy_rows(0, 50).unwrap();
419        assert!(
420            in_progress.size() >= source_size + 50 * size_of::<i32>(),
421            "values buffer under-counted: {} < {} + {} * {}",
422            in_progress.size(),
423            source_size,
424            50,
425            size_of::<i32>(),
426        );
427
428        // finish() takes the buffered values/nulls but keeps the source, so the
429        // reported size drops back to exactly the source.
430        in_progress.finish().unwrap();
431        assert_eq!(in_progress.size(), source_size);
432    }
433
434    #[test]
435    fn test_size_counts_null_buffer() {
436        const BATCH_SIZE: usize = 64;
437
438        let in_progress_bytes = |source: ArrayRef| {
439            let mut in_progress =
440                InProgressPrimitiveArray::<Int32Type>::new(BATCH_SIZE, DataType::Int32);
441            let source_len = source.len();
442            in_progress.set_source(Some(source));
443            in_progress.copy_rows(0, source_len / 2).unwrap();
444            in_progress.size()
445        };
446
447        // All values valid: the nulls builder never allocates.
448        let all_valid = in_progress_bytes(Arc::new(Int32Array::from_iter_values(0..100)));
449        // Some values null: copying materializes a null buffer that must count.
450        let with_nulls = in_progress_bytes(Arc::new(Int32Array::from_iter(
451            (0..100).map(|i| (i % 2 == 0).then_some(i)),
452        )));
453
454        assert!(
455            with_nulls > all_valid,
456            "null buffer must be included in size(): with_nulls={with_nulls} all_valid={all_valid}"
457        );
458    }
459
460    #[test]
461    fn test_copy_rows_by_indices() {
462        let source: ArrayRef = Arc::new(Int32Array::from_iter(
463            (0..32i32).map(|i| if i % 3 == 0 { None } else { Some(i) }),
464        ));
465        let indices = UInt32Array::from(vec![
466            0u32, 15, 2, 7, 3, 9, 12, 1, 20, 15, 6, 8, 11, 18, 21, 24, 30,
467        ]);
468
469        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(32, DataType::Int32);
470        // SAFETY: `indices` contains no nulls and every index is less than `source.len()`.
471        unsafe { in_progress.copy_rows_by_indices(&source, &indices).unwrap() };
472        let actual = in_progress.finish().unwrap();
473
474        let expected = take(source.as_ref(), &indices, None).unwrap();
475        assert_eq!(actual.as_ref(), expected.as_ref());
476    }
477}