jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1774233692


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -0,0 +1,456 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+use datafusion_common::utils::proxy::VecAllocExt;
+
+use std::sync::Arc;
+use std::vec;
+
+use datafusion_physical_expr_common::binary_map::{OutputType, 
INITIAL_BUFFER_CAPACITY};
+
+/// Trait for group values column-wise row comparison
+///
+/// Implementations of this trait store a in-progress collection of group 
values
+/// (similar to various builders in Arrow-rs) that allow for quick comparison 
to
+/// incoming rows.
+///
+pub trait ArrayRowEq: Send + Sync {
+    /// Returns equal if the row stored in this builder at `lhs_row` is equal 
to
+    /// the row in `array` at `rhs_row`
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    /// Appends the row at `row` in `array` to this builder
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    /// Returns the number of rows stored in this builder
+    fn len(&self) -> usize;
+    /// Returns the number of bytes used by this [`ArrayRowEq`]
+    fn size(&self) -> usize;
+    /// Builds a new array from all of the stored rows
+    fn build(self: Box<Self>) -> ArrayRef;
+    /// Builds a new array from the first `n` stored rows, shifting the
+    /// remaining rows to the start of the builder
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
+    group_values: Vec<T::Native>,
+    nulls: Vec<bool>,
+    // whether the array contains at least one null, for fast non-null path
+    has_null: bool,
+    nullable: bool,
+}
+
+impl<T> PrimitiveGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+{
+    pub fn new(nullable: bool) -> Self {
+        Self {
+            group_values: vec![],
+            nulls: vec![],
+            has_null: false,
+            nullable,
+        }
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        // non-null fast path
+        // both non-null
+        if !self.nullable {
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        // lhs is non-null
+        if self.nulls[lhs_row] {
+            if array.is_null(rhs_row) {
+                return false;
+            }
+
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        array.is_null(rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) {
+        if self.nullable && array.is_null(row) {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        } else {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn size(&self) -> usize {
+        self.group_values.allocated_size() + self.nulls.allocated_size()
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        if self.has_null {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                Some(NullBuffer::from(self.nulls)),
+            ))
+        } else {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                None,
+            ))
+        }
+    }
+
+    fn take_n(&mut self, n: usize) -> ArrayRef {
+        if self.has_null {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(first_n),
+                Some(NullBuffer::from(first_n_nulls)),
+            ))
+        } else {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            self.nulls.truncate(self.nulls.len() - n);
+            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), 
None))
+        }
+    }
+}
+
+pub struct ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    output_type: OutputType,
+    buffer: BufferBuilder<u8>,
+    /// Offsets into `buffer` for each distinct  value. These offsets as used
+    /// directly to create the final `GenericBinaryArray`. The `i`th string is
+    /// stored in the range `offsets[i]..offsets[i+1]` in `buffer`. Null values
+    /// are stored as a zero length string.
+    offsets: Vec<O>,
+    /// Null indexes in offsets, if `i` is in nulls, `offsets[i]` should be 
equals to `offsets[i+1]`
+    nulls: Vec<usize>,

Review Comment:
   It is not easy to handle `take_n` logic with `BooleanBufferBuilder`



-- 
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: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to