This is an automated email from the ASF dual-hosted git repository.

Jefffrey pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new 66b91a581e introduce `GenericByteDictionaryBuilder::append_array()` 
(#10765)
66b91a581e is described below

commit 66b91a581e2eb9a077f04c32ba07ce9082d34cc0
Author: RIchard Baah <[email protected]>
AuthorDate: Mon Aug 24 00:52:28 2026 -0400

    introduce `GenericByteDictionaryBuilder::append_array()` (#10765)
    
    # Which issue does this PR close?
    
    <!--
    We generally require a GitHub issue to be filed for all bug fixes and
    enhancements and this helps us generate change logs for our releases.
    You can link an issue to this PR using the GitHub syntax.
    -->
    
    - Closes #10762.
    
    # Rationale for this change
    
    the utf8/binary -> dict<_,utf8/binary> currently calls `append_value()`
    in a loop even when it has the entire array ahead of time. this PR
    avoids that by working with th entire array at once as well as branching
    on weather or not the array contains nulls.
    
    <!--
    Why are you proposing this change? If this is already explained clearly
    in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand
    your changes and offer better suggestions for fixes.
    -->
    
    # What changes are included in this PR?
    new `append_array()` method on the byteDictionaryBuilder.
    <!--
    There is no need to duplicate the description in the issue here but it
    is sometimes worth providing a summary of the individual changes in this
    PR.
    -->
    
    # Are these changes tested?
    yes & benchmarked
    <!--
    We typically require tests for all PRs in order to:
    1. Prevent the code from being accidentally broken by subsequent changes
    2. Serve as another way to document the expected behavior of the code
    
    If tests are not included in your PR, please explain why (for example,
    are they covered by existing tests)?
    
    If this PR claims a performance improvement, please include evidence
    such as benchmark results.
    -->
    
    # Are there any user-facing changes?
    yes, new `append_array()` method on the byteDictionaryBuilder.
    <!--
    If there are user-facing changes then we may require documentation to be
    updated before approving the PR.
    
    If there are any breaking changes to public APIs, please call them out.
    -->
---
 .../builder/generic_bytes_dictionary_builder.rs    | 168 ++++++++++++++++++++-
 arrow-cast/src/cast/dictionary.rs                  |  10 +-
 2 files changed, 168 insertions(+), 10 deletions(-)

diff --git a/arrow-array/src/builder/generic_bytes_dictionary_builder.rs 
b/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
index a399e6e4f9..67d02ee6b6 100644
--- a/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
+++ b/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
@@ -377,6 +377,63 @@ where
         }
     }
 
+    /// Append all values from a [`GenericByteArray`] into this builder.
+    ///
+    /// This is more efficient than calling [`Self::append`] in a loop because
+    /// it accesses the raw offset/value buffers directly and bulk-writes the
+    /// resolved keys with a single `append_slice` / `append_values` call.
+    ///
+    /// Returns an error if any new dictionary index would overflow the key 
type.
+    pub fn append_array(&mut self, array: &GenericByteArray<T>) -> Result<(), 
ArrowError> {
+        let row_count = array.len();
+        if row_count == 0 {
+            return Ok(());
+        }
+        let offsets = array.value_offsets();
+        let raw_data = array.value_data();
+
+        match array.nulls() {
+            None => {
+                let mut key_buf: Vec<K::Native> = 
Vec::with_capacity(row_count);
+                for row_idx in 0..row_count {
+                    key_buf.push(resolve_key::<K, T>(
+                        row_idx,
+                        offsets,
+                        raw_data,
+                        array,
+                        &mut self.dedup,
+                        &self.state,
+                        &mut self.values_builder,
+                    )?);
+                }
+                self.keys_builder.append_slice(&key_buf);
+            }
+            Some(nulls) => {
+                let mut key_buf: Vec<K::Native> = 
Vec::with_capacity(row_count);
+                let mut valid_buf: Vec<bool> = Vec::with_capacity(row_count);
+                for row_idx in 0..row_count {
+                    if nulls.is_null(row_idx) {
+                        key_buf.push(K::Native::usize_as(0));
+                        valid_buf.push(false);
+                    } else {
+                        key_buf.push(resolve_key::<K, T>(
+                            row_idx,
+                            offsets,
+                            raw_data,
+                            array,
+                            &mut self.dedup,
+                            &self.state,
+                            &mut self.values_builder,
+                        )?);
+                        valid_buf.push(true);
+                    }
+                }
+                self.keys_builder.append_values(&key_buf, &valid_buf);
+            }
+        }
+        Ok(())
+    }
+
     /// Extends builder with an existing dictionary array.
     ///
     /// This is the same as [`Self::extend`] but is faster as it translates
@@ -516,6 +573,41 @@ impl<K: ArrowDictionaryKeyType, T: ByteArrayType, V: 
AsRef<T::Native>> Extend<Op
     }
 }
 
+#[inline]
+fn resolve_key<K, T>(
+    row_idx: usize,
+    offsets: &[T::Offset],
+    raw_data: &[u8],
+    array: &GenericByteArray<T>,
+    dedup: &mut HashTable<usize>,
+    state: &ahash::RandomState,
+    storage: &mut GenericByteBuilder<T>,
+) -> Result<K::Native, ArrowError>
+where
+    K: ArrowDictionaryKeyType,
+    T: ByteArrayType,
+{
+    let start = offsets[row_idx].as_usize();
+    let end = offsets[row_idx + 1].as_usize();
+    // SAFETY: offsets are valid by GenericByteArray invariants
+    let bytes = unsafe { raw_data.get_unchecked(start..end) };
+    let hash = state.hash_one(bytes);
+    let dict_idx = *dedup
+        .entry(
+            hash,
+            |idx| bytes == get_bytes(storage, *idx),
+            |idx| state.hash_one(get_bytes(storage, *idx)),
+        )
+        .or_insert_with(|| {
+            let idx = storage.len();
+            // SAFETY: row_idx < row_count = array.len(), slot is non-null
+            storage.append_value(unsafe { array.value_unchecked(row_idx) });
+            idx
+        })
+        .get();
+    
K::Native::from_usize(dict_idx).ok_or(ArrowError::DictionaryKeyOverflowError)
+}
+
 fn get_bytes<T: ByteArrayType>(values: &GenericByteBuilder<T>, idx: usize) -> 
&[u8] {
     let offsets = values.offsets_slice();
     let values = values.values_slice();
@@ -607,7 +699,9 @@ mod tests {
 
     use crate::array::Int8Array;
     use crate::cast::AsArray;
-    use crate::types::{Int8Type, Int16Type, Int32Type, UInt8Type, UInt16Type, 
Utf8Type};
+    use crate::types::{
+        BinaryType, Int8Type, Int16Type, Int32Type, UInt8Type, UInt16Type, 
Utf8Type,
+    };
     use crate::{ArrowPrimitiveType, BinaryArray, StringArray};
 
     fn test_bytes_dictionary_builder<T>(values: Vec<&T::Native>)
@@ -1108,4 +1202,76 @@ mod tests {
             [Some("a"), Some("b"), Some("c"), Some("d"), Some("e"),]
         );
     }
+
+    #[test]
+    fn test_append_array_deduplicates_repeated_values() {
+        let input = StringArray::from(vec!["a", "b", "a", "c", "b", "a"]);
+
+        let mut builder = GenericByteDictionaryBuilder::<Int8Type, 
Utf8Type>::new();
+        builder.append_array(&input).unwrap();
+        let result = builder.finish();
+
+        let mut expected_builder = GenericByteDictionaryBuilder::<Int8Type, 
Utf8Type>::new();
+        for value in &input {
+            expected_builder.append_option(value);
+        }
+        let expected = expected_builder.finish();
+
+        assert_eq!(result.keys().values(), expected.keys().values());
+        assert_eq!(result.values().len(), 3);
+    }
+
+    #[test]
+    fn test_append_array_dedup_across_consecutive_calls() {
+        let first = StringArray::from(vec!["a", "b"]);
+        let second = StringArray::from(vec!["b", "c", "a"]);
+
+        let mut builder = GenericByteDictionaryBuilder::<Int8Type, 
Utf8Type>::new();
+        builder.append_array(&first).unwrap();
+        builder.append_array(&second).unwrap();
+        let result = builder.finish();
+
+        assert_eq!(result.keys().values(), &[0, 1, 1, 2, 0]);
+        assert_eq!(result.values().len(), 3);
+    }
+
+    #[test]
+    fn test_append_array_preserves_null_positions() {
+        let input = StringArray::from(vec![Some("x"), None, Some("x"), None, 
Some("y")]);
+
+        let mut builder = GenericByteDictionaryBuilder::<Int8Type, 
Utf8Type>::new();
+        builder.append_array(&input).unwrap();
+        let result = builder.finish();
+
+        let mut expected_builder = GenericByteDictionaryBuilder::<Int8Type, 
Utf8Type>::new();
+        for value in &input {
+            expected_builder.append_option(value);
+        }
+        let expected = expected_builder.finish();
+
+        assert_eq!(result.keys(), expected.keys());
+        assert_eq!(result.values().len(), 2);
+    }
+
+    #[test]
+    fn test_append_array_overflow_binary() {
+        // Int8 keys hold at most 128 distinct values (indices 0..=127).
+        // Inserting a 129th distinct entry must return 
DictionaryKeyOverflowError.
+        let distinct_values: Vec<Option<Vec<u8>>> = (0u16..=128)
+            .map(|n| Some(n.to_string().into_bytes()))
+            .collect();
+        let input = BinaryArray::from_opt_vec(
+            distinct_values
+                .iter()
+                .map(|v| v.as_deref())
+                .collect::<Vec<_>>(),
+        );
+
+        let mut builder = GenericByteDictionaryBuilder::<Int8Type, 
BinaryType>::new();
+        let result = builder.append_array(&input);
+        assert!(
+            matches!(result, Err(ArrowError::DictionaryKeyOverflowError)),
+            "expected DictionaryKeyOverflowError, got {result:?}"
+        );
+    }
 }
diff --git a/arrow-cast/src/cast/dictionary.rs 
b/arrow-cast/src/cast/dictionary.rs
index 0acf12922a..25e247e16f 100644
--- a/arrow-cast/src/cast/dictionary.rs
+++ b/arrow-cast/src/cast/dictionary.rs
@@ -659,15 +659,7 @@ where
             ArrowError::ComputeError("Internal Error: Cannot cast to 
GenericByteArray".to_string())
         })?;
     let mut b = GenericByteDictionaryBuilder::<K, 
T>::with_capacity(values.len(), 1024, 1024);
-
-    // copy each element one at a time
-    for i in 0..values.len() {
-        if values.is_null(i) {
-            b.append_null();
-        } else {
-            b.append(values.value(i))?;
-        }
-    }
+    b.append_array(values)?;
     Ok(Arc::new(b.finish()))
 }
 

Reply via email to