Rich-T-kid commented on code in PR #11696:
URL: https://github.com/apache/arrow-rs/pull/11696#discussion_r4338776464


##########
arrow-select/src/coalesce/byte.rs:
##########
@@ -0,0 +1,469 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use super::{InProgressArray, should_use_byte_array_direct_copy};
+use crate::concat::concat;
+use crate::filter::{FilterIndices, FilterPredicate, FilterSelection};
+use arrow_array::cast::AsArray;
+use arrow_array::types::ByteArrayType;
+use arrow_array::{Array, ArrayRef, GenericByteArray, OffsetSizeTrait};
+use arrow_buffer::{
+    ArrowNativeType, Buffer, NullBuffer, NullBufferBuilder, OffsetBuffer, 
ScalarBuffer,
+};
+use arrow_schema::ArrowError;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+struct DirectState<O> {
+    /// In-progress nulls
+    nulls: NullBufferBuilder,
+    /// In-progress offsets
+    offsets: Vec<O>,
+    /// In-progress values
+    values: Vec<u8>,
+}
+
+impl<O: ArrowNativeType> DirectState<O> {
+    fn new(rows: usize, bytes: usize) -> Self {
+        let mut offsets = Vec::with_capacity(rows.saturating_add(1));
+        offsets.push(O::usize_as(0));
+        Self {
+            nulls: NullBufferBuilder::new(rows),
+            offsets,
+            values: Vec::with_capacity(bytes),
+        }
+    }
+}
+
+/// InProgressArray for [`GenericByteArray`]
+pub(crate) struct InProgressByteArray<T: ByteArrayType> {
+    /// The current source
+    source: Option<ArrayRef>,
+    /// Is [`Self::source`] referenced in [`Self::buffered_arrays`]
+    source_data_referenced_in_buffers: bool,
+    /// The buffered array slices
+    buffered_arrays: Vec<ArrayRef>,
+    /// The number of bytes the arrays in [`Self::buffered_arrays`] takes
+    total_size_of_non_shared_buffers: usize,
+    /// The in-progress directly copied values
+    direct: Option<Box<DirectState<T::Offset>>>,
+    /// The byte array type
+    _phantom: PhantomData<T>,
+}
+
+impl<T: ByteArrayType> std::fmt::Debug for InProgressByteArray<T> {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("InProgressByteArray")
+            .field("buffered_arrays", &self.buffered_arrays.len())
+            .field(
+                "direct_rows",
+                &self
+                    .direct
+                    .as_ref()
+                    .map_or(0, |state| state.offsets.len().saturating_sub(1)),
+            )
+            .finish()
+    }
+}
+
+impl<T: ByteArrayType> InProgressByteArray<T>
+where
+    T::Offset: OffsetSizeTrait,
+{
+    pub(crate) fn new() -> Self {
+        Self {
+            source: None,
+            source_data_referenced_in_buffers: false,
+            buffered_arrays: Vec::new(),
+            total_size_of_non_shared_buffers: 0,
+            direct: None,
+            _phantom: PhantomData,
+        }
+    }
+
+    fn ensure_direct(&mut self, source: &GenericByteArray<T>, rows: usize) {
+        self.direct.get_or_insert_with(|| {
+            let offsets = source.value_offsets();
+            let bytes = if source.is_empty() {
+                0
+            } else {
+                let source_bytes = offsets[source.len()].as_usize() - 
offsets[0].as_usize();
+                source_bytes.saturating_mul(rows) / source.len()
+            };
+            Box::new(DirectState::new(rows, bytes))
+        });
+    }
+
+    fn checked_values_len(current: usize, additional: usize) -> Result<usize, 
ArrowError> {
+        let new_len = current
+            .checked_add(additional)
+            .ok_or(ArrowError::OffsetOverflowError(usize::MAX))?;
+        if new_len > T::Offset::MAX_OFFSET {
+            return Err(ArrowError::OffsetOverflowError(new_len));
+        }
+        Ok(new_len)
+    }
+
+    fn flush_direct(&mut self) {
+        let Some(mut state) = self.direct.take() else {
+            return;
+        };
+        if state.offsets.len() == 1 {
+            return;
+        }
+
+        let array = GenericByteArray::<T>::new(
+            OffsetBuffer::new(ScalarBuffer::from(state.offsets)),
+            Buffer::from_vec(state.values),
+            state.nulls.finish(),
+        );
+        let array: ArrayRef = Arc::new(array);
+        self.total_size_of_non_shared_buffers += array.get_array_memory_size();
+        self.buffered_arrays.push(array);
+    }
+
+    fn append_filter_nulls(
+        nulls: &mut NullBufferBuilder,
+        source_nulls: Option<&NullBuffer>,
+        filter: &FilterPredicate,
+    ) {
+        if let Some(filtered) = filter.filter_nulls(source_nulls) {
+            nulls.append_buffer(&filtered);
+        } else {
+            nulls.append_n_non_nulls(filter.count());
+        }
+    }
+
+    fn append_filter_indices(
+        &mut self,
+        source: &GenericByteArray<T>,
+        filter: &FilterPredicate,
+        indices: FilterIndices<'_>,
+    ) -> Result<(), ArrowError> {
+        self.ensure_direct(source, filter.count());
+        let state = self.direct.as_mut().expect("direct state initialized");
+        Self::append_filter_nulls(&mut state.nulls, source.nulls(), filter);
+        state.offsets.reserve(filter.count());
+
+        let source_offsets = source.value_offsets();
+        let source_values = source.value_data();
+        indices.try_for_each(|idx| {
+            let start = source_offsets[idx].as_usize();
+            let end = source_offsets[idx + 1].as_usize();
+            let new_len = Self::checked_values_len(state.values.len(), end - 
start)?;
+            state.values.reserve(new_len - state.values.len());
+            state.values.extend_from_slice(&source_values[start..end]);
+            state.offsets.push(
+                T::Offset::from_usize(state.values.len())
+                    
.ok_or(ArrowError::OffsetOverflowError(state.values.len()))?,
+            );

Review Comment:
   Updated in d8037488b3. The direct path now computes and validates the total 
selected byte length first, reserves the values buffer once, and then copies 
the selected values in a second pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to