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

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit b3427f5e819226b7c434b734825ae04989abb588
Author: RIchard Baah <[email protected]>
AuthorDate: Fri Nov 6 02:58:54 2026 +0000

    perf(arrow): coalesce dictionary keys without concat (#11743)
    
    # Which issue does this PR close?
    
    Closes #11719.
    
    # Rationale for this change
    
    Dictionary arrays currently use the generic coalescer path, which
    retains input arrays and calls `concat` when a batch is emitted.
    Dictionary-heavy workloads therefore repeat value merging and hashing
    and keep more input memory alive than necessary.
    
    # What changes are included in this PR?
    
    This adds a dictionary-specific in-progress array for byte-array values.
    It retains zero-copy slices of the key buffers and stores each values
    `Arc` once.
    
    ## Merging distinct values arrays
    
    When every chunk uses the same values `Arc`, `finish` reuses it
    directly. Otherwise, `merge_dictionary_values_with_masks` marks only the
    referenced values, builds a local-to-output key mapping for each source,
    and calls `interleave` once to write the final values array. This only
    gathers dictionary values; the stored keys are remapped directly into
    the final key buffer, with no filtered dictionary arrays or `concat` in
    between.
    
    For example, start with three dictionary arrays:
    
    ```text
    A = DictionaryArray {
        keys:   [3, 1, 4, 0, 2, 1, 3, 4, 0, 2]
        values: ["red", "blue", "green", "black", "orange"]
    }
    
    B = DictionaryArray {
        keys:   [2, 0, 3, 1, 0, 2, 1, 3, 2, 0]
        values: ["cyan", "purple", "gray", "gold"]
    }
    
    C = DictionaryArray {
        keys:   [4, 2, 1, 3, 0, 4, 1, 2, 3, 0]
        values: ["teal", "red", "purple", "pink", "green"]
    }
    ```
    
    Each call retains a multi-row key slice in its original local key space:
    
    ```text
    copy_rows(A, 2, 4) -> (source A, keys [4, 0, 2, 1])
    copy_rows(B, 3, 4) -> (source B, keys [1, 0, 2, 1])
    copy_rows(C, 1, 5) -> (source C, keys [2, 1, 3, 0, 4])
    
    sources:  0 -> A.values
              1 -> B.values
              2 -> C.values
    
    chunks:   (source 0, [4, 0, 2, 1])
              (source 1, [1, 0, 2, 1])
              (source 2, [2, 1, 3, 0, 4])
    ```
    
    At flush, only the referenced values are appended and each local key is
    mapped to its output position:
    
    ```text
    output values: ["red", "blue", "green", "orange", "cyan", "purple",
                    "gray", "teal", "red", "purple", "pink", "green"]
    
    remaps:  A: 0 -> 0, 1 -> 1, 2 -> 2, 4 -> 3
             B: 0 -> 4, 1 -> 5, 2 -> 6
             C: 0 -> 7, 1 -> 8, 2 -> 9, 3 -> 10, 4 -> 11
    
    output keys: [3, 0, 2, 1, 5, 4, 6, 5, 9, 8, 10, 7, 11]
    decoded:     ["orange", "red", "green", "blue", "purple", "cyan", "gray",
                  "purple", "purple", "red", "pink", "teal", "green"]
    ```
    
    The direct path keeps repeated values from different sources because the
    12 referenced values fit the key type. If they did not fit, the fallback
    would deduplicate the shared values from C:
    
    ```text
    deduplicated values: ["red", "blue", "green", "orange", "cyan", "purple",
                          "gray", "teal", "pink"]
    
    C remap: 0 -> 7, 1 -> 0, 2 -> 5, 3 -> 8, 4 -> 2
    ```
    
    # Are these changes tested?
    
    The tests cover shared and distinct values arrays, alternating sources,
    sparse remapping, null keys, row order, direct values reuse, and
    key-type overflow fallback.
    
    Two final-head
    
[hosted](https://github.com/apache/arrow-rs/pull/11743#issuecomment-6570137044)
    
[runs](https://github.com/apache/arrow-rs/pull/11743#issuecomment-6570129351)
    show large filter and take gains, smaller interleave gains, and peak
    memory dropping from 63 MiB to 23 MiB.
    
    # Are there any significant user-facing changes?
    
    No.
---
 arrow-select/src/coalesce.rs            |   5 +
 arrow-select/src/coalesce/dictionary.rs | 395 ++++++++++++++++++++++++++++++++
 arrow-select/src/dictionary.rs          |  98 +++++++-
 3 files changed, 494 insertions(+), 4 deletions(-)

diff --git a/arrow-select/src/coalesce.rs b/arrow-select/src/coalesce.rs
index 2acf9900f0..57bf0f7874 100644
--- a/arrow-select/src/coalesce.rs
+++ b/arrow-select/src/coalesce.rs
@@ -21,6 +21,7 @@ use std::sync::Arc;
 mod boolean;
 mod byte;
 mod byte_view;
+mod dictionary;
 mod fixed_size_binary;
 mod generic;
 mod list;
@@ -29,6 +30,7 @@ mod primitive;
 use boolean::InProgressBooleanArray;
 use byte::InProgressByteArray;
 use byte_view::InProgressByteViewArray;
+use dictionary::create_in_progress_dictionary;
 use fixed_size_binary::InProgressFixedSizeBinaryArray;
 use generic::GenericInProgressArray;
 use list::InProgressListArray;
@@ -825,6 +827,9 @@ fn create_in_progress_array(data_type: &DataType, 
batch_size: usize) -> Box<dyn
         DataType::LargeBinary => {
             
Box::new(InProgressByteArray::<GenericBinaryType<i64>>::new(batch_size))
         }
+        DataType::Dictionary(key, value) => {
+            create_in_progress_dictionary(key, value)
+        }
         DataType::FixedSizeBinary(size) => {
             Box::new(InProgressFixedSizeBinaryArray::new(*size, batch_size))
         }
diff --git a/arrow-select/src/coalesce/dictionary.rs 
b/arrow-select/src/coalesce/dictionary.rs
new file mode 100644
index 0000000000..99c126ea97
--- /dev/null
+++ b/arrow-select/src/coalesce/dictionary.rs
@@ -0,0 +1,395 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use super::{InProgressArray, generic::GenericInProgressArray};
+use crate::dictionary::{child_values_ptr_eq, 
merge_dictionary_values_with_masks};
+use ahash::RandomState;
+use arrow_array::cast::AsArray;
+use arrow_array::types::ArrowDictionaryKeyType;
+use arrow_array::{
+    Array, ArrayRef, DictionaryArray, PrimitiveArray, downcast_integer, 
new_empty_array,
+};
+use arrow_buffer::{
+    ArrowNativeType, BooleanBufferBuilder, NullBuffer, NullBufferBuilder, 
ScalarBuffer,
+};
+use arrow_schema::{ArrowError, DataType};
+use std::collections::HashMap;
+use std::mem::size_of;
+use std::sync::Arc;
+
+struct KeyChunk<K: ArrowDictionaryKeyType> {
+    /// Zero-copy slice of source-local keys for the retained rows.
+    keys: ScalarBuffer<K::Native>,
+    /// Shared validity buffer from the source keys, if present.
+    nulls: Option<NullBuffer>,
+    /// Index of the values array in `InProgressDictionaryArray::sources`.
+    source: usize,
+}
+
+pub(crate) fn create_in_progress_dictionary(
+    key_type: &DataType,
+    value_type: &DataType,
+) -> Box<dyn InProgressArray> {
+    macro_rules! create {
+        ($key:ty, $value_type:ident) => {
+            Box::new(InProgressDictionaryArray::<$key>::new($value_type))
+        };
+    }
+
+    match value_type {
+        DataType::Utf8 | DataType::LargeUtf8 | DataType::Binary | 
DataType::LargeBinary => {
+            downcast_integer! {
+                key_type => (create, value_type),
+                _ => unreachable!("illegal dictionary key type {key_type}"),
+            }
+        }
+        _ => Box::new(GenericInProgressArray::new()),
+    }
+}
+
+struct InProgressDictionaryArray<K: ArrowDictionaryKeyType> {
+    /// Dictionary currently selected by [`InProgressArray::set_source`].
+    source: Option<ArrayRef>,
+    /// Number of output rows retained across `chunks`.
+    len: usize,
+    /// Typed empty values array used when finishing without any rows.
+    empty_values: ArrayRef,
+    /// Distinct dictionary values arrays retained by buffer identity.
+    sources: Vec<ArrayRef>,
+    /// Maps each retained values `Arc` address to its index in `sources`.
+    source_ids: HashMap<usize, usize, RandomState>,
+    /// Zero-copy key slices in output order, tagged with their values source.
+    chunks: Vec<KeyChunk<K>>,
+}
+
+impl<K: ArrowDictionaryKeyType> std::fmt::Debug for 
InProgressDictionaryArray<K> {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("InProgressDictionaryArray").finish()
+    }
+}
+
+impl<K: ArrowDictionaryKeyType> InProgressDictionaryArray<K> {
+    fn new(value_type: &DataType) -> Self {
+        Self {
+            source: None,
+            len: 0,
+            empty_values: new_empty_array(value_type),
+            sources: Vec::new(),
+            source_ids: HashMap::with_hasher(RandomState::with_seeds(0, 0, 0, 
0)),
+            chunks: Vec::new(),
+        }
+    }
+
+    /// Returns a stable index for `values`, reusing a source when either its 
`Arc`
+    /// pointer or its backing buffer pointers match.
+    fn source_id(&mut self, values: ArrayRef) -> usize {
+        if let Some(last) = self.chunks.last()
+            && child_values_ptr_eq(&self.sources[last.source], &values)
+        {
+            return last.source;
+        }
+        let values_id = Arc::as_ptr(&values).cast::<()>() as usize;
+        if let Some(&source) = self.source_ids.get(&values_id) {
+            return source;
+        }
+        if let Some(source) = self
+            .sources
+            .iter()
+            .position(|existing| child_values_ptr_eq(existing, &values))
+        {
+            return source;
+        }
+        let source = self.sources.len();
+        self.sources.push(values);
+        self.source_ids.insert(values_id, source);
+        source
+    }
+
+    /// Compacts referenced values and remaps source-local keys while 
preserving chunk order.
+    /// Equal referenced values are only deduplicated when their count would 
overflow
+    /// `K`'s key space.
+    fn merge_sources(
+        sources: &[ArrayRef],
+        chunks: &[KeyChunk<K>],
+        len: usize,
+    ) -> Result<(Vec<K::Native>, ArrayRef), ArrowError> {
+        let mut referenced = sources
+            .iter()
+            .map(|source| {
+                let mut mask = BooleanBufferBuilder::new(source.len());
+                mask.advance(source.len());
+                mask
+            })
+            .collect::<Vec<_>>();
+
+        for chunk in chunks {
+            let mask = &mut referenced[chunk.source];
+            match &chunk.nulls {
+                Some(nulls) => nulls
+                    .inner()
+                    .set_indices()
+                    .for_each(|offset| 
mask.set_bit(chunk.keys[offset].as_usize(), true)),
+                None => chunk
+                    .keys
+                    .iter()
+                    .for_each(|key| mask.set_bit(key.as_usize(), true)),
+            }
+        }
+
+        let referenced = referenced
+            .into_iter()
+            .map(BooleanBufferBuilder::build)
+            .collect::<Vec<_>>();
+        let source_refs = sources
+            .iter()
+            .map(|source| source.as_ref() as &dyn Array)
+            .collect::<Vec<_>>();
+        let merged = merge_dictionary_values_with_masks::<K>(&source_refs, 
&referenced)?;
+
+        let mut keys = Vec::with_capacity(len);
+        for chunk in chunks {
+            let mapping = &merged.key_mappings[chunk.source];
+            match &chunk.nulls {
+                Some(nulls) => 
keys.extend(chunk.keys.iter().enumerate().map(|(offset, key)| {
+                    if nulls.is_valid(offset) {
+                        mapping[key.as_usize()]
+                    } else {
+                        K::Native::default()
+                    }
+                })),
+                None => keys.extend(chunk.keys.iter().map(|key| 
mapping[key.as_usize()])),
+            }
+        }
+        Ok((keys, merged.values))
+    }
+
+    /// Concatenates chunk validity in output order, omitting it when all keys 
are valid.
+    fn build_nulls(chunks: &[KeyChunk<K>], len: usize) -> Option<NullBuffer> {
+        let mut nulls = NullBufferBuilder::new(len);
+        for chunk in chunks {
+            match &chunk.nulls {
+                Some(chunk_nulls) => nulls.append_buffer(chunk_nulls),
+                None => nulls.append_n_non_nulls(chunk.keys.len()),
+            }
+        }
+        nulls.finish()
+    }
+}
+
+impl<K: ArrowDictionaryKeyType> InProgressArray for 
InProgressDictionaryArray<K> {
+    fn set_source(&mut self, source: Option<ArrayRef>) {
+        self.source = source;
+    }
+
+    fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), 
ArrowError> {
+        if len == 0 {
+            return Ok(());
+        }
+        let source = Arc::clone(self.source.as_ref().ok_or_else(|| {
+            ArrowError::InvalidArgumentError(
+                "Internal Error: InProgressDictionaryArray: source not 
set".to_string(),
+            )
+        })?);
+        let dictionary = source.as_dictionary::<K>();
+        let keys = dictionary.keys();
+        let source = self.source_id(Arc::clone(dictionary.values()));
+        self.chunks.push(KeyChunk {
+            keys: keys.values().slice(offset, len),
+            nulls: keys.nulls().map(|nulls| nulls.slice(offset, len)),
+            source,
+        });
+        self.len += len;
+        Ok(())
+    }
+
+    fn finish(&mut self) -> Result<ArrayRef, ArrowError> {
+        let sources = std::mem::take(&mut self.sources);
+        let chunks = std::mem::take(&mut self.chunks);
+        let len = std::mem::take(&mut self.len);
+        self.source_ids.clear();
+
+        let (keys, values) = match sources.len() {
+            0 => (Vec::new(), Arc::clone(&self.empty_values)),
+            1 => (
+                chunks
+                    .iter()
+                    .flat_map(|chunk| chunk.keys.iter().copied())
+                    .collect(),
+                Arc::clone(&sources[0]),
+            ),
+            _ => Self::merge_sources(&sources, &chunks, len)?,
+        };
+        let nulls = Self::build_nulls(&chunks, len);
+        let keys = PrimitiveArray::<K>::try_new(ScalarBuffer::from(keys), 
nulls)?;
+        Ok(Arc::new(DictionaryArray::try_new(keys, values)?))
+    }
+
+    /// Estimates memory retained by the source, value arrays, key slices, and 
bookkeeping.
+    fn size(&self) -> usize {
+        self.source
+            .as_ref()
+            .map_or(0, |source| source.get_array_memory_size())
+            + self
+                .sources
+                .iter()
+                .map(|source| source.get_array_memory_size())
+                .sum::<usize>()
+            + self.sources.capacity() * size_of::<ArrayRef>()
+            + self.source_ids.capacity() * size_of::<(usize, usize)>()
+            + self.chunks.capacity() * size_of::<KeyChunk<K>>()
+            + self
+                .chunks
+                .iter()
+                .map(|chunk| {
+                    chunk.keys.inner().capacity()
+                        + chunk
+                            .nulls
+                            .as_ref()
+                            .map_or(0, |nulls| 
nulls.inner().inner().capacity())
+                })
+                .sum::<usize>()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::coalesce::BatchCoalescer;
+    use arrow_array::types::{Int8Type, Int32Type};
+    use arrow_array::{Int8Array, Int32Array, RecordBatch, StringArray};
+
+    fn batch(values: &ArrayRef, keys: Vec<Option<i32>>) -> RecordBatch {
+        let dictionary = Arc::new(DictionaryArray::<Int32Type>::new(
+            Int32Array::from(keys),
+            Arc::clone(values),
+        )) as ArrayRef;
+        RecordBatch::try_from_iter([("dict", dictionary)]).unwrap()
+    }
+
+    #[test]
+    fn coalesces_repeated_and_distinct_values() {
+        let first_values = Arc::new(StringArray::from(vec!["a", "b"])) as 
ArrayRef;
+        let second_values = Arc::new(StringArray::from(vec!["b", "c"])) as 
ArrayRef;
+        let batches = [
+            batch(&first_values, vec![Some(0), None]),
+            batch(&second_values, vec![Some(0), Some(1)]),
+            batch(&first_values, vec![Some(1), Some(0)]),
+        ];
+        let mut coalescer = BatchCoalescer::new(batches[0].schema(), 6);
+        for batch in batches {
+            coalescer.push_batch(batch).unwrap();
+        }
+
+        let output = coalescer.next_completed_batch().unwrap();
+        let output = output.column(0).as_dictionary::<Int32Type>();
+        let values = output.values().as_string::<i32>();
+        let decoded = output
+            .keys_iter()
+            .map(|key| key.map(|key| values.value(key)))
+            .collect::<Vec<_>>();
+        assert_eq!(
+            decoded,
+            vec![Some("a"), None, Some("b"), Some("c"), Some("b"), Some("a")]
+        );
+        assert_eq!(values.len(), 4);
+    }
+
+    #[test]
+    fn reuses_one_values_array() {
+        let values = Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef;
+        let mut coalescer = BatchCoalescer::new(batch(&values, 
vec![Some(0)]).schema(), 2);
+        coalescer.push_batch(batch(&values, vec![Some(0)])).unwrap();
+        coalescer.push_batch(batch(&values, vec![Some(1)])).unwrap();
+
+        let output = coalescer.next_completed_batch().unwrap();
+        let output = output.column(0).as_dictionary::<Int32Type>();
+        assert!(Arc::ptr_eq(output.values(), &values));
+    }
+
+    #[test]
+    fn reuses_values_with_shared_buffers() {
+        let values = StringArray::from_iter_values((0..128).map(|i| 
format!("value-{i}")));
+        let first_values = Arc::new(values.clone()) as ArrayRef;
+        let second_values = Arc::new(values) as ArrayRef;
+        let make_batch = |values| {
+            let dictionary =
+                
DictionaryArray::<Int8Type>::new(Int8Array::from_iter_values(0..=127), values);
+            RecordBatch::try_from_iter([("dict", Arc::new(dictionary) as 
ArrayRef)]).unwrap()
+        };
+
+        let first = make_batch(Arc::clone(&first_values));
+        let mut coalescer = BatchCoalescer::new(first.schema(), 256);
+        coalescer.push_batch(first).unwrap();
+        coalescer.push_batch(make_batch(second_values)).unwrap();
+
+        let output = coalescer.next_completed_batch().unwrap();
+        let output = output.column(0).as_dictionary::<Int8Type>();
+        assert!(Arc::ptr_eq(output.values(), &first_values));
+        assert_eq!(
+            output.keys().values(),
+            &(0..=127).chain(0..=127).collect::<Vec<_>>()
+        );
+    }
+
+    #[test]
+    fn remaps_sparse_values_across_sources() {
+        let first = Arc::new(DictionaryArray::<Int32Type>::new(
+            Int32Array::from_iter_values([1, 2, 0, 2, 1]),
+            Arc::new(StringArray::from(vec!["a", "unused-a", "b"])),
+        )) as ArrayRef;
+        let second = Arc::new(DictionaryArray::<Int32Type>::new(
+            Int32Array::from_iter_values([2, 1, 0, 1, 2]),
+            Arc::new(StringArray::from(vec!["b", "c", "unused-b"])),
+        )) as ArrayRef;
+
+        let mut in_progress = 
InProgressDictionaryArray::<Int32Type>::new(&DataType::Utf8);
+        in_progress.set_source(Some(first));
+        in_progress.copy_rows(1, 3).unwrap();
+        in_progress.set_source(Some(second));
+        in_progress.copy_rows(1, 3).unwrap();
+
+        let output = in_progress.finish().unwrap();
+        let output = output.as_dictionary::<Int32Type>();
+        assert_eq!(output.keys().values(), &[1, 0, 1, 3, 2, 3]);
+        assert_eq!(
+            output
+                .values()
+                .as_string::<i32>()
+                .iter()
+                .collect::<Vec<_>>(),
+            vec![Some("a"), Some("b"), Some("b"), Some("c")]
+        );
+    }
+
+    #[test]
+    fn remaps_keys_when_deduplication_is_required() {
+        let make_values = || {
+            Arc::new(StringArray::from_iter_values(
+                (0..70).map(|idx| format!("value-{idx}")),
+            )) as ArrayRef
+        };
+        let first_values = make_values();
+        let second_values = make_values();
+        let make_dictionary = |values| {
+            Arc::new(DictionaryArray::<Int8Type>::new(
+                Int8Array::from_iter_values(0..70),
+                values,
+            )) as ArrayRef
+        };
+
+        let mut in_progress = 
InProgressDictionaryArray::<Int8Type>::new(&DataType::Utf8);
+        in_progress.set_source(Some(make_dictionary(first_values)));
+        in_progress.copy_rows(0, 70).unwrap();
+        in_progress.set_source(Some(make_dictionary(second_values)));
+        in_progress.copy_rows(0, 70).unwrap();
+
+        let output = in_progress.finish().unwrap();
+        let output = output.as_dictionary::<Int8Type>();
+        let values = output.values().as_string::<i32>();
+        for (idx, key) in output.keys().values().iter().enumerate() {
+            assert_eq!(values.value(*key as usize), format!("value-{}", idx % 
70));
+        }
+        assert!(values.len() <= i8::MAX as usize + 1);
+    }
+}
diff --git a/arrow-select/src/dictionary.rs b/arrow-select/src/dictionary.rs
index f4638a06b0..47e3a13bf6 100644
--- a/arrow-select/src/dictionary.rs
+++ b/arrow-select/src/dictionary.rs
@@ -161,10 +161,6 @@ fn bytes_ptr_eq<T: ByteArrayType>(a: &dyn Array, b: &dyn 
Array) -> bool {
 /// different buffers return `false`. Arrays with no allocated storage, such 
as two empty
 /// primitive arrays built from empty `Vec`s or two 
[`arrow_array::NullArray`]s of the same
 /// length, return `true`.
-#[cfg_attr(
-    not(test),
-    expect(dead_code, reason = "used by the dictionary coalescer in #11743")
-)]
 pub(crate) fn child_values_ptr_eq(left: &ArrayRef, right: &ArrayRef) -> bool {
     if Arc::ptr_eq(left, right) {
         return true;
@@ -306,6 +302,83 @@ pub(crate) fn merge_dictionary_values<K: 
ArrowDictionaryKeyType>(
     })
 }
 
+/// Merges referenced entries from multiple dictionary values arrays.
+///
+/// `values_masks[i]` corresponds to `values_arrays[i]`, with each set bit 
identifying a
+/// value to retain. Returns the merged values and a mapping from each source 
value index
+/// to its index in the merged array. Mapping entries for unreferenced values 
are zero and
+/// must not be used.
+///
+/// Referenced values are gathered without hashing when their count fits in 
`K`'s key space,
+/// preserving duplicates across sources. Otherwise, values are deduplicated 
on a best-effort
+/// basis to avoid key overflow.
+pub(crate) fn merge_dictionary_values_with_masks<K: ArrowDictionaryKeyType>(
+    values_arrays: &[&dyn Array],
+    values_masks: &[BooleanBuffer],
+) -> Result<MergedDictionaries<K>, ArrowError> {
+    assert_eq!(values_arrays.len(), values_masks.len());
+    let num_values = 
values_masks.iter().map(BooleanBuffer::count_set_bits).sum();
+
+    // Dictionary values need not be unique. Avoid hashing when the referenced 
value count
+    // fits in `K`'s key space, and only deduplicate to avoid overflow.
+    if num_values == 0 || K::Native::from_usize(num_values - 1).is_some() {
+        let zero = K::Native::from_usize(0).unwrap();
+        let mut indices = Vec::with_capacity(num_values);
+        let key_mappings = values_arrays
+            .iter()
+            .zip(values_masks)
+            .enumerate()
+            .map(|(dictionary_idx, (values, mask))| {
+                let mut mapping = vec![zero; values.len()];
+                for value_idx in mask.set_indices() {
+                    mapping[value_idx] = 
K::Native::from_usize(indices.len()).unwrap();
+                    indices.push((dictionary_idx, value_idx));
+                }
+                mapping
+            })
+            .collect();
+        return Ok(MergedDictionaries {
+            key_mappings,
+            values: interleave(values_arrays, &indices)?,
+        });
+    }
+
+    let value_slices = values_arrays
+        .iter()
+        .zip(values_masks)
+        .map(|(values, mask)| get_masked_values(*values, mask))
+        .collect::<Vec<_>>();
+    let mut interner = Interner::new(num_values);
+    let mut indices = Vec::with_capacity(num_values);
+
+    let key_mappings = values_arrays
+        .iter()
+        .enumerate()
+        .zip(value_slices)
+        .map(|((dictionary_idx, value_array), values)| {
+            let zero = K::Native::ZERO;
+            let mut mapping = vec![zero; value_array.len()];
+
+            for (value_idx, value) in values {
+                mapping[value_idx] =
+                    *interner.intern(value, || match 
K::Native::from_usize(indices.len()) {
+                        Some(idx) => {
+                            indices.push((dictionary_idx, value_idx));
+                            Ok(idx)
+                        }
+                        None => Err(ArrowError::DictionaryKeyOverflowError),
+                    })?;
+            }
+            Ok(mapping)
+        })
+        .collect::<Result<Vec<_>, ArrowError>>()?;
+
+    Ok(MergedDictionaries {
+        key_mappings,
+        values: interleave(values_arrays, &indices)?,
+    })
+}
+
 /// Return a mask identifying the values that are referenced by keys in 
`dictionary`
 /// at the positions indicated by `selection`
 fn compute_values_mask<K: ArrowNativeType>(
@@ -614,6 +687,23 @@ mod tests {
         assert_eq!(&merged.key_mappings[1], &[2, 3, 1, 4]);
     }
 
+    #[test]
+    fn test_merge_dictionary_values_with_masks() {
+        let first = StringArray::from_iter_values(["a", "unused-a", "shared"]);
+        let second = StringArray::from_iter_values(["shared", "b", 
"unused-b"]);
+        let values = [&first as &dyn Array, &second as &dyn Array];
+        let masks = [
+            BooleanBuffer::from_iter([true, false, true]),
+            BooleanBuffer::from_iter([true, true, false]),
+        ];
+
+        let merged = merge_dictionary_values_with_masks::<Int32Type>(&values, 
&masks).unwrap();
+
+        let expected = StringArray::from_iter_values(["a", "shared", "shared", 
"b"]);
+        assert_eq!(merged.values.as_ref(), &expected);
+        assert_eq!(merged.key_mappings, vec![vec![0, 0, 1], vec![2, 3, 0]]);
+    }
+
     #[test]
     fn test_merge_nulls() {
         let buffer = Buffer::from(b"helloworldbingohelloworld");

Reply via email to