arrow_select/coalesce/
primitive.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::coalesce::InProgressArray;
19use arrow_array::cast::AsArray;
20use arrow_array::{Array, ArrayRef, ArrowPrimitiveType, PrimitiveArray};
21use arrow_buffer::{NullBufferBuilder, ScalarBuffer};
22use arrow_schema::ArrowError;
23use std::fmt::Debug;
24use std::sync::Arc;
25
26/// InProgressArray for [`PrimitiveArray`]
27#[derive(Debug)]
28pub(crate) struct InProgressPrimitiveArray<T: ArrowPrimitiveType> {
29    /// The current source, if any
30    source: Option<ArrayRef>,
31    /// the target batch size (and thus size for views allocation)
32    batch_size: usize,
33    /// In progress nulls
34    nulls: NullBufferBuilder,
35    /// The currently in progress array
36    current: Vec<T::Native>,
37}
38
39impl<T: ArrowPrimitiveType> InProgressPrimitiveArray<T> {
40    /// Create a new `InProgressPrimitiveArray`
41    pub(crate) fn new(batch_size: usize) -> Self {
42        Self {
43            batch_size,
44            source: None,
45            nulls: NullBufferBuilder::new(batch_size),
46            current: vec![],
47        }
48    }
49
50    /// Allocate space for output values if necessary.
51    ///
52    /// This is done on write (when we know it is necessary) rather than
53    /// eagerly to avoid allocations that are not used.
54    fn ensure_capacity(&mut self) {
55        self.current.reserve(self.batch_size);
56    }
57}
58
59impl<T: ArrowPrimitiveType + Debug> InProgressArray for InProgressPrimitiveArray<T> {
60    fn set_source(&mut self, source: Option<ArrayRef>) {
61        self.source = source;
62    }
63
64    fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), ArrowError> {
65        self.ensure_capacity();
66
67        let s = self
68            .source
69            .as_ref()
70            .ok_or_else(|| {
71                ArrowError::InvalidArgumentError(
72                    "Internal Error: InProgressPrimitiveArray: source not set".to_string(),
73                )
74            })?
75            .as_primitive::<T>();
76
77        // add nulls if necessary
78        if let Some(nulls) = s.nulls().as_ref() {
79            let nulls = nulls.slice(offset, len);
80            self.nulls.append_buffer(&nulls);
81        } else {
82            self.nulls.append_n_non_nulls(len);
83        };
84
85        // Copy the values
86        self.current
87            .extend_from_slice(&s.values()[offset..offset + len]);
88
89        Ok(())
90    }
91
92    fn finish(&mut self) -> Result<ArrayRef, ArrowError> {
93        // take and reset the current values and nulls
94        let values = std::mem::take(&mut self.current);
95        let nulls = self.nulls.finish();
96        self.nulls = NullBufferBuilder::new(self.batch_size);
97
98        let array = PrimitiveArray::<T>::try_new(ScalarBuffer::from(values), nulls)?;
99        Ok(Arc::new(array))
100    }
101}