Skip to main content

datafusion_common/
hash_utils.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Functionality used both on logical and physical plans
6
7use arrow::array::types::{IntervalDayTime, IntervalMonthDayNano};
8use arrow::array::*;
9#[cfg(not(feature = "force_hash_collisions"))]
10use arrow::buffer::ScalarBuffer;
11#[cfg(not(feature = "force_hash_collisions"))]
12use arrow::compute::{nullif, take};
13use arrow::datatypes::*;
14#[cfg(not(feature = "force_hash_collisions"))]
15use arrow::{downcast_dictionary_array, downcast_primitive_array};
16use foldhash::fast::FixedState;
17#[cfg(not(feature = "force_hash_collisions"))]
18use itertools::Itertools;
19use std::hash::{BuildHasher, Hash, Hasher};
20
21/// [`RandomState`] is optimized for speed and suitable for hash tables and
22/// bloom filters. [`QualityRandomState`] is optimized for statistical quality
23/// and suitable for algorithms such as HyperLogLog. The tradeoff is that the
24/// fast variant gives up some statistical quality, while the quality variant
25/// is slightly slower.
26///
27/// See: <https://docs.rs/foldhash/0.2.0/src/foldhash/lib.rs.html#17-21>
28pub type RandomState = FixedState;
29pub type QualityRandomState = foldhash::quality::FixedState;
30
31/// Fixed quality hash state used by HyperLogLog sketches.
32///
33/// The seed is part of the HLL wire/storage semantics: serialized sketches only
34/// remain mergeable if every producer uses the same hash state.
35pub const HLL_RANDOM_STATE: QualityRandomState = QualityRandomState::with_seed(0);
36
37/// Hash state used by [`create_hashes`].
38///
39/// Multi-column hashing folds the previous column hash into a fresh hasher
40/// before hashing the next column. This trait keeps that seeded hasher in the
41/// same foldhash tier as the top-level hash state.
42pub trait HashState: BuildHasher {
43    type SeededState: BuildHasher;
44
45    fn seeded_state(&self, seed: u64) -> Self::SeededState;
46}
47
48impl HashState for FixedState {
49    type SeededState = foldhash::fast::SeedableRandomState;
50
51    fn seeded_state(&self, seed: u64) -> Self::SeededState {
52        foldhash::fast::SeedableRandomState::with_seed(
53            seed,
54            foldhash::SharedSeed::global_fixed(),
55        )
56    }
57}
58
59impl HashState for foldhash::quality::FixedState {
60    type SeededState = foldhash::quality::SeedableRandomState;
61
62    fn seeded_state(&self, seed: u64) -> Self::SeededState {
63        foldhash::quality::SeedableRandomState::with_seed(
64            seed,
65            foldhash::SharedSeed::global_fixed(),
66        )
67    }
68}
69
70#[cfg(not(feature = "force_hash_collisions"))]
71use crate::cast::{
72    as_binary_view_array, as_boolean_array, as_fixed_size_list_array,
73    as_generic_binary_array, as_large_list_array, as_large_list_view_array,
74    as_list_array, as_list_view_array, as_map_array, as_string_array,
75    as_string_view_array, as_struct_array, as_union_array,
76};
77use crate::error::Result;
78use crate::error::{_internal_datafusion_err, _internal_err};
79use crate::float_semantics::hash_input;
80#[cfg(not(feature = "force_hash_collisions"))]
81use crate::utils::offset_span;
82use std::cell::RefCell;
83
84mod build_hasher;
85
86// Combines two hashes into one hash
87#[inline]
88pub fn combine_hashes(l: u64, r: u64) -> u64 {
89    let hash = (17 * 37u64).wrapping_add(l);
90    hash.wrapping_mul(37).wrapping_add(r)
91}
92
93/// Maximum size for the thread-local hash buffer before truncation (4MB = 524,288 u64 elements).
94/// The goal of this is to avoid unbounded memory growth that would appear as a memory leak.
95/// We allow temporary allocations beyond this size, but after use the buffer is truncated
96/// to this size.
97const MAX_BUFFER_SIZE: usize = 524_288;
98
99thread_local! {
100    /// Thread-local buffer for hash computations to avoid repeated allocations.
101    /// The buffer is reused across calls and truncated if it exceeds MAX_BUFFER_SIZE.
102    /// Defaults to a capacity of 8192 u64 elements which is the default batch size.
103    /// This corresponds to 64KB of memory.
104    static HASH_BUFFER: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
105}
106
107/// Creates hashes for the given arrays using a thread-local buffer, then calls the provided callback
108/// with an immutable reference to the computed hashes.
109///
110/// This function manages a thread-local buffer to avoid repeated allocations. The buffer is automatically
111/// truncated if it exceeds `MAX_BUFFER_SIZE` after use.
112///
113/// # Arguments
114/// * `arrays` - The arrays to hash (must contain at least one array)
115/// * `random_state` - The random state for hashing
116/// * `callback` - A function that receives an immutable reference to the hash slice and returns a result
117///
118/// # Errors
119/// Returns an error if:
120/// - No arrays are provided
121/// - The function is called reentrantly (i.e., the callback invokes `with_hashes` again on the same thread)
122/// - The function is called during or after thread destruction
123///
124/// # Example
125/// ```ignore
126/// use datafusion_common::hash_utils::{with_hashes, RandomState};
127/// use arrow::array::{Int32Array, ArrayRef};
128/// use std::sync::Arc;
129///
130/// let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
131/// let random_state = RandomState::default();
132///
133/// let result = with_hashes([&array], &random_state, |hashes| {
134///     // Use the hashes here
135///     Ok(hashes.len())
136/// })?;
137/// ```
138pub fn with_hashes<I, T, F, R>(
139    arrays: I,
140    random_state: &impl HashState,
141    callback: F,
142) -> Result<R>
143where
144    I: IntoIterator<Item = T>,
145    T: AsDynArray,
146    F: FnOnce(&[u64]) -> Result<R>,
147{
148    // Peek at the first array to determine buffer size without fully collecting
149    let mut iter = arrays.into_iter().peekable();
150
151    // Get the required size from the first array
152    let required_size = match iter.peek() {
153        Some(arr) => arr.as_dyn_array().len(),
154        None => return _internal_err!("with_hashes requires at least one array"),
155    };
156
157    HASH_BUFFER.try_with(|cell| {
158        let mut buffer = cell.try_borrow_mut()
159            .map_err(|_| _internal_datafusion_err!("with_hashes cannot be called reentrantly on the same thread"))?;
160
161        // Ensure buffer has sufficient length, clearing old values
162        buffer.clear();
163        buffer.resize(required_size, 0);
164
165        // Create hashes in the buffer - this consumes the iterator
166        create_hashes(iter, random_state, &mut buffer[..required_size])?;
167
168        // Execute the callback with an immutable slice
169        let result = callback(&buffer[..required_size])?;
170
171        // Cleanup: truncate if buffer grew too large
172        if buffer.capacity() > MAX_BUFFER_SIZE {
173            buffer.truncate(MAX_BUFFER_SIZE);
174            buffer.shrink_to_fit();
175        }
176
177        Ok(result)
178    }).map_err(|_| _internal_datafusion_err!("with_hashes cannot access thread-local storage during or after thread destruction"))?
179}
180
181/// Creates hashes for the given arrays using a thread-local buffer and a custom
182/// hash builder, then calls the provided callback with the computed hashes.
183///
184/// Hash compatibility with [`with_hashes`] follows the rules documented on
185/// [`create_hashes_with_hasher`].
186pub fn with_hashes_with_hasher<I, T, F, R, S>(
187    arrays: I,
188    hash_builder: &S,
189    callback: F,
190) -> Result<R>
191where
192    I: IntoIterator<Item = T>,
193    T: AsDynArray,
194    F: FnOnce(&[u64]) -> Result<R>,
195    S: BuildHasher,
196{
197    build_hasher::with_hashes_with_hasher(arrays, hash_builder, callback)
198}
199
200#[cfg(not(feature = "force_hash_collisions"))]
201fn hash_null<S: HashState>(
202    random_state: &S,
203    hashes_buffer: &'_ mut [u64],
204    multi_col: bool,
205) {
206    if multi_col {
207        for hash in hashes_buffer {
208            // stable hash for null value
209            *hash = combine_hashes(random_state.hash_one(1), *hash);
210        }
211    } else {
212        for hash in hashes_buffer {
213            *hash = random_state.hash_one(1);
214        }
215    }
216}
217
218pub trait HashValue {
219    fn hash_one<S: BuildHasher>(&self, state: &S) -> u64;
220    /// Write this value into an existing hasher (same data as `hash_one`).
221    fn hash_write(&self, hasher: &mut impl Hasher);
222}
223
224impl<T: HashValue + ?Sized> HashValue for &T {
225    fn hash_one<S: BuildHasher>(&self, state: &S) -> u64 {
226        T::hash_one(self, state)
227    }
228    fn hash_write(&self, hasher: &mut impl Hasher) {
229        T::hash_write(self, hasher)
230    }
231}
232
233macro_rules! hash_value {
234    ($($t:ty),+) => {
235        $(impl HashValue for $t {
236            fn hash_one<S: BuildHasher>(&self, state: &S) -> u64 {
237                state.hash_one(self)
238            }
239            fn hash_write(&self, hasher: &mut impl Hasher) {
240                Hash::hash(self, hasher)
241            }
242        })+
243    };
244}
245hash_value!(i8, i16, i32, i64, i128, i256, u8, u16, u32, u64, u128);
246hash_value!(bool, str, [u8], IntervalDayTime, IntervalMonthDayNano);
247
248macro_rules! hash_float_value {
249    ($($t:ty),+) => {
250        $(impl HashValue for $t {
251            // Hash the normalized bits so values SQL considers equal
252            // (e.g. +0.0 and -0.0) hash the same.
253            fn hash_one<S: BuildHasher>(&self, state: &S) -> u64 {
254                state.hash_one(hash_input(*self).to_bits())
255            }
256            fn hash_write(&self, hasher: &mut impl Hasher) {
257                hasher.write(&hash_input(*self).to_bits().to_ne_bytes())
258            }
259        })+
260    };
261}
262hash_float_value!(half::f16, f32, f64);
263
264#[cfg(not(feature = "force_hash_collisions"))]
265trait ChildHashing {
266    fn create_hashes<I, T>(&self, arrays: I, hashes_buffer: &mut [u64]) -> Result<()>
267    where
268        I: IntoIterator<Item = T>,
269        T: AsDynArray;
270}
271
272#[cfg(not(feature = "force_hash_collisions"))]
273struct HashStateChildHashing<'a, S> {
274    hash_state: &'a S,
275}
276
277#[cfg(not(feature = "force_hash_collisions"))]
278impl<S: HashState> ChildHashing for HashStateChildHashing<'_, S> {
279    fn create_hashes<I, T>(&self, arrays: I, hashes_buffer: &mut [u64]) -> Result<()>
280    where
281        I: IntoIterator<Item = T>,
282        T: AsDynArray,
283    {
284        create_hashes(arrays, self.hash_state, hashes_buffer).map(|_| ())
285    }
286}
287
288/// Builds hash values of PrimitiveArray and writes them into `hashes_buffer`
289/// If `rehash==true` this folds the existing hash into the hasher state
290/// and hashes only the new value (avoiding a separate combine step).
291#[cfg(not(feature = "force_hash_collisions"))]
292fn hash_array_primitive<T>(
293    array: &PrimitiveArray<T>,
294    random_state: &impl HashState,
295    hashes_buffer: &mut [u64],
296    rehash: bool,
297) where
298    T: ArrowPrimitiveType<Native: HashValue>,
299{
300    assert_eq!(
301        hashes_buffer.len(),
302        array.len(),
303        "hashes_buffer and array should be of equal length"
304    );
305
306    if array.null_count() == 0 {
307        if rehash {
308            hash_prim_rehash_dense(array.values(), hashes_buffer, random_state);
309        } else {
310            hash_prim_fresh_dense(array.values(), hashes_buffer, random_state);
311        }
312    } else if rehash {
313        for i in array.nulls().unwrap().valid_indices() {
314            let value = unsafe { array.value_unchecked(i) };
315            let mut hasher = random_state.seeded_state(hashes_buffer[i]).build_hasher();
316            value.hash_write(&mut hasher);
317            hashes_buffer[i] = hasher.finish();
318        }
319    } else {
320        for i in array.nulls().unwrap().valid_indices() {
321            let value = unsafe { array.value_unchecked(i) };
322            hashes_buffer[i] = value.hash_one(random_state);
323        }
324    }
325}
326
327/// Overwrite each slot with `value.hash_one(state)`, 16 rows per iteration.
328/// Gathering + hashing a whole lane batch before storing keeps the independent
329/// hashes in flight so the pipeline isn't serialized on store-to-load deps.
330#[cfg(not(feature = "force_hash_collisions"))]
331#[inline(always)]
332fn hash_prim_fresh_dense<N, S>(values: &[N], hashes: &mut [u64], state: &S)
333where
334    N: HashValue + Copy,
335    S: HashState,
336{
337    const LANES: usize = 16;
338    let (value_chunks, value_tail) = values.as_chunks::<LANES>();
339    let (hash_chunks, hash_tail) = hashes.as_chunks_mut::<LANES>();
340    for (h, v) in hash_chunks.iter_mut().zip(value_chunks) {
341        *h = v.map(|value| value.hash_one(state));
342    }
343    for (h, v) in hash_tail.iter_mut().zip(value_tail) {
344        *h = v.hash_one(state);
345    }
346}
347
348/// Fold `prev_hash` + `value` into a new hash, 8 rows per iteration. 8 is
349/// narrower than `hash_prim_fresh_dense` because each lane holds both `prev` and
350/// `value` live; widening past 8 spilled registers in the multi-column case.
351#[cfg(not(feature = "force_hash_collisions"))]
352#[inline(always)]
353fn hash_prim_rehash_dense<N, S>(values: &[N], hashes: &mut [u64], state: &S)
354where
355    N: HashValue + Copy,
356    S: HashState,
357{
358    const LANES: usize = 8;
359    let rehash_one = |prev_hash: u64, value: N| {
360        let mut hasher = state.seeded_state(prev_hash).build_hasher();
361        value.hash_write(&mut hasher);
362        hasher.finish()
363    };
364    let (value_chunks, value_tail) = values.as_chunks::<LANES>();
365    let (hash_chunks, hash_tail) = hashes.as_chunks_mut::<LANES>();
366    for (h, v) in hash_chunks.iter_mut().zip(value_chunks) {
367        *h = std::array::from_fn(|lane| rehash_one(h[lane], v[lane]));
368    }
369    for (h, &v) in hash_tail.iter_mut().zip(value_tail) {
370        *h = rehash_one(*h, v);
371    }
372}
373
374/// Hashes one array into the `hashes_buffer`
375/// If `rehash==true` this combines the previous hash value in the buffer
376/// with the new hash using `combine_hashes`
377#[cfg(not(feature = "force_hash_collisions"))]
378fn hash_array<T>(
379    array: &T,
380    random_state: &impl HashState,
381    hashes_buffer: &mut [u64],
382    rehash: bool,
383) where
384    T: ArrayAccessor,
385    T::Item: HashValue,
386{
387    assert_eq!(
388        hashes_buffer.len(),
389        array.len(),
390        "hashes_buffer and array should be of equal length"
391    );
392
393    if array.null_count() == 0 {
394        if rehash {
395            for (i, hash) in hashes_buffer.iter_mut().enumerate() {
396                let value = unsafe { array.value_unchecked(i) };
397                *hash = combine_hashes(value.hash_one(random_state), *hash);
398            }
399        } else {
400            for (i, hash) in hashes_buffer.iter_mut().enumerate() {
401                let value = unsafe { array.value_unchecked(i) };
402                *hash = value.hash_one(random_state);
403            }
404        }
405    } else if rehash {
406        for i in array.nulls().unwrap().valid_indices() {
407            let value = unsafe { array.value_unchecked(i) };
408            hashes_buffer[i] =
409                combine_hashes(value.hash_one(random_state), hashes_buffer[i]);
410        }
411    } else {
412        for i in array.nulls().unwrap().valid_indices() {
413            let value = unsafe { array.value_unchecked(i) };
414            hashes_buffer[i] = value.hash_one(random_state);
415        }
416    }
417}
418
419/// Hash a StringView or BytesView array
420///
421/// Templated to optimize inner loop based on presence of nulls and external buffers.
422///
423/// HAS_NULLS: do we have to check null in the inner loop
424/// HAS_BUFFERS: if true, array has external buffers; if false, all strings are inlined/ less then 12 bytes
425/// REHASH: if true, combining with existing hash, otherwise initializing
426#[cfg(not(feature = "force_hash_collisions"))]
427#[inline(never)]
428fn hash_string_view_array_inner<
429    T: ByteViewType,
430    const HAS_NULLS: bool,
431    const HAS_BUFFERS: bool,
432    const REHASH: bool,
433>(
434    array: &GenericByteViewArray<T>,
435    random_state: &impl HashState,
436    hashes_buffer: &mut [u64],
437) {
438    assert_eq!(
439        hashes_buffer.len(),
440        array.len(),
441        "hashes_buffer and array should be of equal length"
442    );
443
444    let buffers = array.data_buffers();
445    let view_bytes = |view_len: u32, view: u128| {
446        let view = ByteView::from(view);
447        let offset = view.offset as usize;
448        // SAFETY: view is a valid view as it came from the array
449        unsafe {
450            let data = buffers.get_unchecked(view.buffer_index as usize);
451            data.get_unchecked(offset..offset + view_len as usize)
452        }
453    };
454
455    let hashes_and_views = hashes_buffer.iter_mut().zip(array.views().iter());
456    for (i, (hash, &v)) in hashes_and_views.enumerate() {
457        if HAS_NULLS && array.is_null(i) {
458            continue;
459        }
460        let view_len = v as u32;
461        // all views are inlined, no need to access external buffers
462        if !HAS_BUFFERS || view_len <= 12 {
463            if REHASH {
464                let mut hasher = random_state.seeded_state(*hash).build_hasher();
465                v.hash_write(&mut hasher);
466                *hash = hasher.finish();
467            } else {
468                *hash = v.hash_one(random_state);
469            }
470            continue;
471        }
472        // view is not inlined, so we need to hash the bytes as well
473        let value = view_bytes(view_len, v);
474        if REHASH {
475            let mut hasher = random_state.seeded_state(*hash).build_hasher();
476            value.hash_write(&mut hasher);
477            *hash = hasher.finish();
478        } else {
479            *hash = value.hash_one(random_state);
480        }
481    }
482}
483
484/// Builds hash values for array views and writes them into `hashes_buffer`
485/// If `rehash==true` this combines the previous hash value in the buffer
486/// with the new hash using `combine_hashes`
487#[cfg(not(feature = "force_hash_collisions"))]
488fn hash_generic_byte_view_array<T: ByteViewType>(
489    array: &GenericByteViewArray<T>,
490    random_state: &impl HashState,
491    hashes_buffer: &mut [u64],
492    rehash: bool,
493) {
494    // instantiate the correct version based on presence of nulls and external buffers
495    match (
496        array.null_count() != 0,
497        !array.data_buffers().is_empty(),
498        rehash,
499    ) {
500        // no nulls or buffers ==> hash the inlined views directly
501        // don't call the inner function as Rust seems better able to inline this simpler code (2-3% faster)
502        (false, false, false) => {
503            for (hash, &view) in hashes_buffer.iter_mut().zip(array.views().iter()) {
504                *hash = view.hash_one(random_state);
505            }
506        }
507        (false, false, true) => {
508            for (hash, &view) in hashes_buffer.iter_mut().zip(array.views().iter()) {
509                let mut hasher = random_state.seeded_state(*hash).build_hasher();
510                view.hash_write(&mut hasher);
511                *hash = hasher.finish();
512            }
513        }
514        (false, true, false) => hash_string_view_array_inner::<T, false, true, false>(
515            array,
516            random_state,
517            hashes_buffer,
518        ),
519        (false, true, true) => hash_string_view_array_inner::<T, false, true, true>(
520            array,
521            random_state,
522            hashes_buffer,
523        ),
524        (true, false, false) => hash_string_view_array_inner::<T, true, false, false>(
525            array,
526            random_state,
527            hashes_buffer,
528        ),
529        (true, false, true) => hash_string_view_array_inner::<T, true, false, true>(
530            array,
531            random_state,
532            hashes_buffer,
533        ),
534        (true, true, false) => hash_string_view_array_inner::<T, true, true, false>(
535            array,
536            random_state,
537            hashes_buffer,
538        ),
539        (true, true, true) => hash_string_view_array_inner::<T, true, true, true>(
540            array,
541            random_state,
542            hashes_buffer,
543        ),
544    }
545}
546
547/// Scatter precomputed dictionary value hashes to key positions.
548///
549/// Uses const generics to eliminate runtime branching in the hot loop:
550/// - `HAS_NULL_KEYS`: Whether to check for null dictionary keys
551/// - `HAS_NULL_VALUES`: Whether to check for null dictionary values
552/// - `MULTI_COL`: Whether to combine with existing hash (true) or initialize (false)
553#[cfg(not(feature = "force_hash_collisions"))]
554#[inline(never)]
555fn hash_dictionary_scatter<
556    K: ArrowDictionaryKeyType,
557    const HAS_NULL_KEYS: bool,
558    const HAS_NULL_VALUES: bool,
559    const MULTI_COL: bool,
560>(
561    array: &DictionaryArray<K>,
562    dict_hashes: &[u64],
563    hashes_buffer: &mut [u64],
564) {
565    let dict_values = array.values();
566    if HAS_NULL_KEYS {
567        for (hash, key) in hashes_buffer.iter_mut().zip(array.keys().iter()) {
568            if let Some(key) = key {
569                let idx = key.as_usize();
570                if !HAS_NULL_VALUES || dict_values.is_valid(idx) {
571                    // SAFETY: `idx` is a valid Arrow dict key, in-bounds for `dict_hashes`.
572                    let dict_hash = unsafe { *dict_hashes.get_unchecked(idx) };
573                    *hash = if MULTI_COL {
574                        combine_hashes(dict_hash, *hash)
575                    } else {
576                        dict_hash
577                    };
578                }
579            }
580        }
581    } else {
582        for (hash, key) in hashes_buffer.iter_mut().zip(array.keys().values()) {
583            let idx = key.as_usize();
584            if !HAS_NULL_VALUES || dict_values.is_valid(idx) {
585                // SAFETY: `idx` is a valid Arrow dict key, in-bounds for `dict_hashes`.
586                let dict_hash = unsafe { *dict_hashes.get_unchecked(idx) };
587                *hash = if MULTI_COL {
588                    combine_hashes(dict_hash, *hash)
589                } else {
590                    dict_hash
591                };
592            }
593        }
594    }
595}
596
597#[cfg(not(feature = "force_hash_collisions"))]
598fn dispatch_dictionary_scatter<K: ArrowDictionaryKeyType>(
599    array: &DictionaryArray<K>,
600    dict_hashes: &[u64],
601    hashes_buffer: &mut [u64],
602    multi_col: bool,
603) {
604    let has_null_keys = array.keys().null_count() != 0;
605    let has_null_values = array.values().null_count() != 0;
606
607    match (has_null_keys, has_null_values, multi_col) {
608        (false, false, false) => hash_dictionary_scatter::<K, false, false, false>(
609            array,
610            dict_hashes,
611            hashes_buffer,
612        ),
613        (false, false, true) => hash_dictionary_scatter::<K, false, false, true>(
614            array,
615            dict_hashes,
616            hashes_buffer,
617        ),
618        (false, true, false) => hash_dictionary_scatter::<K, false, true, false>(
619            array,
620            dict_hashes,
621            hashes_buffer,
622        ),
623        (false, true, true) => hash_dictionary_scatter::<K, false, true, true>(
624            array,
625            dict_hashes,
626            hashes_buffer,
627        ),
628        (true, false, false) => hash_dictionary_scatter::<K, true, false, false>(
629            array,
630            dict_hashes,
631            hashes_buffer,
632        ),
633        (true, false, true) => hash_dictionary_scatter::<K, true, false, true>(
634            array,
635            dict_hashes,
636            hashes_buffer,
637        ),
638        (true, true, false) => hash_dictionary_scatter::<K, true, true, false>(
639            array,
640            dict_hashes,
641            hashes_buffer,
642        ),
643        (true, true, true) => hash_dictionary_scatter::<K, true, true, true>(
644            array,
645            dict_hashes,
646            hashes_buffer,
647        ),
648    }
649}
650
651/// Hash the values in a dictionary array.
652#[cfg(not(feature = "force_hash_collisions"))]
653fn hash_dictionary<K: ArrowDictionaryKeyType>(
654    array: &DictionaryArray<K>,
655    random_state: &impl HashState,
656    hashes_buffer: &mut [u64],
657    multi_col: bool,
658) -> Result<()> {
659    // Hash each dictionary value once, and then use that computed
660    // hash for each key value to avoid a potentially expensive
661    // redundant hashing for large dictionary elements (e.g. strings)
662    let dict_values = array.values();
663    let mut dict_hashes = vec![0; dict_values.len()];
664    create_hashes([dict_values], random_state, &mut dict_hashes)?;
665    dispatch_dictionary_scatter(array, &dict_hashes, hashes_buffer, multi_col);
666    Ok(())
667}
668
669#[cfg(not(feature = "force_hash_collisions"))]
670fn hash_dictionary_with_child_hashing<K: ArrowDictionaryKeyType>(
671    array: &DictionaryArray<K>,
672    child_hashing: &impl ChildHashing,
673    hashes_buffer: &mut [u64],
674    multi_col: bool,
675) -> Result<()> {
676    let dict_values = array.values();
677    let mut dict_hashes = vec![0; dict_values.len()];
678    child_hashing.create_hashes([dict_values], &mut dict_hashes)?;
679    dispatch_dictionary_scatter(array, &dict_hashes, hashes_buffer, multi_col);
680    Ok(())
681}
682
683#[cfg(not(feature = "force_hash_collisions"))]
684fn hash_struct_array(
685    array: &StructArray,
686    child_hashing: &impl ChildHashing,
687    hashes_buffer: &mut [u64],
688) -> Result<()> {
689    let nulls = array.nulls();
690    let row_len = array.len();
691
692    // Create hashes for each row that combines the hashes over all the column at that row.
693    let mut values_hashes = vec![0u64; row_len];
694    child_hashing.create_hashes(array.columns(), &mut values_hashes)?;
695
696    // Separate paths to avoid allocating Vec when there are no nulls
697    if let Some(nulls) = nulls {
698        for i in nulls.valid_indices() {
699            let hash = &mut hashes_buffer[i];
700            *hash = combine_hashes(*hash, values_hashes[i]);
701        }
702    } else {
703        for i in 0..row_len {
704            let hash = &mut hashes_buffer[i];
705            *hash = combine_hashes(*hash, values_hashes[i]);
706        }
707    }
708
709    Ok(())
710}
711
712// only adding this `cfg` b/c this function is only used with this `cfg`
713#[cfg(not(feature = "force_hash_collisions"))]
714fn hash_map_array(
715    array: &MapArray,
716    child_hashing: &impl ChildHashing,
717    hashes_buffer: &mut [u64],
718) -> Result<()> {
719    let nulls = array.nulls();
720    let offsets = array.offsets();
721
722    // Create hashes for each entry in each row
723    let (first_offset, entries_len) = offset_span(offsets);
724
725    // Only hash the entries that are actually referenced
726    let mut values_hashes = vec![0u64; entries_len];
727    let entries = array.entries();
728    let sliced_columns: Vec<ArrayRef> = entries
729        .columns()
730        .iter()
731        .map(|col| col.slice(first_offset, entries_len))
732        .collect();
733    child_hashing.create_hashes(&sliced_columns, &mut values_hashes)?;
734
735    // Combine the hashes for entries on each row with each other and previous hash for that row
736    // Adjust indices by first_offset since values_hashes is sliced starting from first_offset
737    if let Some(nulls) = nulls {
738        for (i, (start, stop)) in offsets.iter().zip(offsets.iter().skip(1)).enumerate() {
739            if nulls.is_valid(i) {
740                let hash = &mut hashes_buffer[i];
741                for values_hash in &values_hashes
742                    [start.as_usize() - first_offset..stop.as_usize() - first_offset]
743                {
744                    *hash = combine_hashes(*hash, *values_hash);
745                }
746            }
747        }
748    } else {
749        for (i, (start, stop)) in offsets.iter().zip(offsets.iter().skip(1)).enumerate() {
750            let hash = &mut hashes_buffer[i];
751            for values_hash in &values_hashes
752                [start.as_usize() - first_offset..stop.as_usize() - first_offset]
753            {
754                *hash = combine_hashes(*hash, *values_hash);
755            }
756        }
757    }
758
759    Ok(())
760}
761
762#[cfg(not(feature = "force_hash_collisions"))]
763fn hash_list_array<OffsetSize>(
764    array: &GenericListArray<OffsetSize>,
765    child_hashing: &impl ChildHashing,
766    hashes_buffer: &mut [u64],
767) -> Result<()>
768where
769    OffsetSize: OffsetSizeTrait,
770{
771    // Hash only the child values referenced by this ListArray's offsets.
772    let (first_offset, values_len) = offset_span(array.offsets());
773    let mut values_hashes = vec![0u64; values_len];
774    child_hashing.create_hashes(
775        [array.values().slice(first_offset, values_len)],
776        &mut values_hashes,
777    )?;
778
779    if array.null_count() > 0 {
780        for (i, (start, stop)) in array.value_offsets().iter().tuple_windows().enumerate()
781        {
782            if array.is_valid(i) {
783                let hash = &mut hashes_buffer[i];
784                for values_hash in &values_hashes
785                    [start.as_usize() - first_offset..stop.as_usize() - first_offset]
786                {
787                    *hash = combine_hashes(*hash, *values_hash);
788                }
789            }
790        }
791    } else {
792        for ((start, stop), hash) in array
793            .value_offsets()
794            .iter()
795            .tuple_windows()
796            .zip(hashes_buffer.iter_mut())
797        {
798            for values_hash in &values_hashes
799                [start.as_usize() - first_offset..stop.as_usize() - first_offset]
800            {
801                *hash = combine_hashes(*hash, *values_hash);
802            }
803        }
804    }
805    Ok(())
806}
807
808#[cfg(not(feature = "force_hash_collisions"))]
809fn hash_list_view_array<OffsetSize>(
810    array: &GenericListViewArray<OffsetSize>,
811    child_hashing: &impl ChildHashing,
812    hashes_buffer: &mut [u64],
813) -> Result<()>
814where
815    OffsetSize: OffsetSizeTrait,
816{
817    let values = array.values();
818    let offsets = array.value_offsets();
819    let sizes = array.value_sizes();
820    let nulls = array.nulls();
821    let mut values_hashes = vec![0u64; values.len()];
822    child_hashing.create_hashes([values], &mut values_hashes)?;
823    if let Some(nulls) = nulls {
824        for (i, (offset, size)) in offsets.iter().zip(sizes.iter()).enumerate() {
825            if nulls.is_valid(i) {
826                let hash = &mut hashes_buffer[i];
827                let start = offset.as_usize();
828                let end = start + size.as_usize();
829                for values_hash in &values_hashes[start..end] {
830                    *hash = combine_hashes(*hash, *values_hash);
831                }
832            }
833        }
834    } else {
835        for (i, (offset, size)) in offsets.iter().zip(sizes.iter()).enumerate() {
836            let hash = &mut hashes_buffer[i];
837            let start = offset.as_usize();
838            let end = start + size.as_usize();
839            for values_hash in &values_hashes[start..end] {
840                *hash = combine_hashes(*hash, *values_hash);
841            }
842        }
843    }
844    Ok(())
845}
846
847#[cfg(not(feature = "force_hash_collisions"))]
848fn hash_union_array(
849    array: &UnionArray,
850    child_hashing: &impl ChildHashing,
851    hashes_buffer: &mut [u64],
852) -> Result<()> {
853    let DataType::Union(union_fields, _mode) = array.data_type() else {
854        unreachable!()
855    };
856
857    if array.is_dense() {
858        hash_dense_union_array(array, union_fields, child_hashing, hashes_buffer)
859    } else {
860        hash_sparse_union_array(array, union_fields, child_hashing, hashes_buffer)
861    }
862}
863
864/// Slicing a dense union does not slice its children, so when their total length
865/// exceeds the union's, only the span its offsets reference is hashed.
866#[cfg(not(feature = "force_hash_collisions"))]
867fn hash_dense_union_array(
868    array: &UnionArray,
869    union_fields: &UnionFields,
870    child_hashing: &impl ChildHashing,
871    hashes_buffer: &mut [u64],
872) -> Result<()> {
873    let type_ids = array.type_ids();
874    let offsets = array.offsets().expect("dense union has offsets");
875
876    // `[start, end)` of each child to hash, indexed by type id
877    let mut spans = [(0, 0); 128];
878    for (type_id, _) in union_fields.iter() {
879        spans[type_id as usize].1 = array.child(type_id).len();
880    }
881    if spans.iter().map(|(_, end)| end).sum::<usize>() > array.len() {
882        spans = [(usize::MAX, 0); 128];
883        for (&type_id, &offset) in type_ids.iter().zip(offsets.iter()) {
884            let (start, end) = &mut spans[type_id as usize];
885            *start = (*start).min(offset as usize);
886            *end = (*end).max(offset as usize + 1);
887        }
888    }
889
890    let mut child_hashes = vec![vec![]; spans.len()];
891    for (type_id, _) in union_fields.iter() {
892        let (start, end) = spans[type_id as usize];
893        if start < end {
894            let child = array.child(type_id).slice(start, end - start);
895            let hashes = &mut child_hashes[type_id as usize];
896            hashes.resize(end - start, 0);
897            child_hashing.create_hashes([child], hashes)?;
898        }
899    }
900
901    for ((hash, &type_id), &offset) in hashes_buffer.iter_mut().zip(type_ids).zip(offsets)
902    {
903        let start = spans[type_id as usize].0;
904        let child_hash = child_hashes[type_id as usize][offset as usize - start];
905        *hash = combine_hashes(*hash, child_hash);
906    }
907
908    Ok(())
909}
910
911/// Each row of a sparse union uses only one child, so each child is hashed
912/// only at the rows that select it.
913#[cfg(not(feature = "force_hash_collisions"))]
914fn hash_sparse_union_array(
915    array: &UnionArray,
916    union_fields: &UnionFields,
917    child_hashing: &impl ChildHashing,
918    hashes_buffer: &mut [u64],
919) -> Result<()> {
920    let type_ids = array.type_ids();
921    let len = array.len();
922
923    // Rows the child hashing skips keep a hash of 0
924    let mut child_hashes = vec![0; len];
925    if let Some(&type_id) = type_ids.first()
926        && type_ids.iter().all(|&t| t == type_id)
927    {
928        child_hashing.create_hashes([array.child(type_id)], &mut child_hashes)?;
929    } else {
930        let (starts, rows) = group_rows_by_type_id(type_ids);
931        let mut taken_hashes: Vec<u64> = Vec::new();
932        for (type_id, _) in union_fields.iter() {
933            let (start, end) = (starts[type_id as usize], starts[type_id as usize + 1]);
934            if start == end {
935                continue;
936            }
937
938            let child = array.child(type_id);
939            let variable_width = matches!(
940                child.data_type(),
941                DataType::Utf8
942                    | DataType::LargeUtf8
943                    | DataType::Binary
944                    | DataType::LargeBinary
945            );
946            // Masking the other rows as null (skipped by hashing) avoids copying
947            // variable-width values but costs O(len) per child, so `take` wins for
948            // fixed-width values and for children selecting few rows
949            if variable_width && (end - start) * 32 >= len {
950                let mut other_rows = BooleanBufferBuilder::new(len);
951                other_rows.append_n(len, true);
952                for &row in &rows[start..end] {
953                    other_rows.set_bit(row as usize, false);
954                }
955                let masked =
956                    nullif(child, &BooleanArray::new(other_rows.finish(), None))?;
957                child_hashing.create_hashes([masked], &mut child_hashes)?;
958            } else {
959                let indices = UInt32Array::new(rows.slice(start, end - start), None);
960                taken_hashes.clear();
961                taken_hashes.resize(indices.len(), 0);
962                child_hashing
963                    .create_hashes([take(child, &indices, None)?], &mut taken_hashes)?;
964                for (&row, &hash) in indices.values().iter().zip(&taken_hashes) {
965                    child_hashes[row as usize] = hash;
966                }
967            }
968        }
969    }
970
971    for (hash, child_hash) in hashes_buffer.iter_mut().zip(child_hashes) {
972        *hash = combine_hashes(*hash, child_hash);
973    }
974
975    Ok(())
976}
977
978/// Counting sort of row indices by type id: the rows of `type_id` are
979/// `rows[starts[type_id]..starts[type_id + 1]]`
980#[cfg(not(feature = "force_hash_collisions"))]
981fn group_rows_by_type_id(type_ids: &[i8]) -> ([usize; 129], ScalarBuffer<u32>) {
982    let mut starts = [0; 129];
983    for &type_id in type_ids {
984        starts[type_id as usize + 1] += 1;
985    }
986    let mut total = 0;
987    for start in &mut starts {
988        total += *start;
989        *start = total;
990    }
991    let mut next = starts;
992    let mut rows = vec![0; type_ids.len()];
993    for (row, &type_id) in type_ids.iter().enumerate() {
994        rows[next[type_id as usize]] = row as u32;
995        next[type_id as usize] += 1;
996    }
997    (starts, rows.into())
998}
999
1000#[cfg(not(feature = "force_hash_collisions"))]
1001fn hash_fixed_list_array(
1002    array: &FixedSizeListArray,
1003    child_hashing: &impl ChildHashing,
1004    hashes_buffer: &mut [u64],
1005) -> Result<()> {
1006    let values = array.values();
1007    let value_length = array.value_length() as usize;
1008    let nulls = array.nulls();
1009    let mut values_hashes = vec![0u64; values.len()];
1010    child_hashing.create_hashes([values], &mut values_hashes)?;
1011    if let Some(nulls) = nulls {
1012        for i in 0..array.len() {
1013            if nulls.is_valid(i) {
1014                let hash = &mut hashes_buffer[i];
1015                for values_hash in
1016                    &values_hashes[i * value_length..(i + 1) * value_length]
1017                {
1018                    *hash = combine_hashes(*hash, *values_hash);
1019                }
1020            }
1021        }
1022    } else {
1023        for i in 0..array.len() {
1024            let hash = &mut hashes_buffer[i];
1025            for values_hash in &values_hashes[i * value_length..(i + 1) * value_length] {
1026                *hash = combine_hashes(*hash, *values_hash);
1027            }
1028        }
1029    }
1030    Ok(())
1031}
1032
1033/// Inner hash function for RunArray
1034#[inline(never)]
1035#[cfg(not(feature = "force_hash_collisions"))]
1036fn hash_run_array_inner<
1037    R: RunEndIndexType,
1038    C: ChildHashing + ?Sized,
1039    const HAS_NULL_VALUES: bool,
1040    const REHASH: bool,
1041>(
1042    array: &RunArray<R>,
1043    child_hashing: &C,
1044    hashes_buffer: &mut [u64],
1045) -> Result<()> {
1046    // We find the relevant runs that cover potentially sliced arrays, so we can only hash those
1047    // values. Then we find the runs that refer to the original runs and ensure that we apply
1048    // hashes correctly to the sliced, whether sliced at the start, end, or both.
1049    let array_offset = array.offset();
1050    let array_len = array.len();
1051
1052    if array_len == 0 {
1053        return Ok(());
1054    }
1055
1056    let run_ends = array.run_ends();
1057    let run_ends_values = run_ends.values();
1058    let values = array.values();
1059
1060    let start_physical_index = array.get_start_physical_index();
1061    // get_end_physical_index returns the inclusive last index, but we need the exclusive range end
1062    // for the operations we use below.
1063    let end_physical_index = array.get_end_physical_index() + 1;
1064
1065    let sliced_values = values.slice(
1066        start_physical_index,
1067        end_physical_index - start_physical_index,
1068    );
1069    let mut values_hashes = vec![0u64; sliced_values.len()];
1070    child_hashing
1071        .create_hashes(std::slice::from_ref(&sliced_values), &mut values_hashes)?;
1072
1073    let mut start_in_slice = 0;
1074    for (adjusted_physical_index, &absolute_run_end) in run_ends_values
1075        [start_physical_index..end_physical_index]
1076        .iter()
1077        .enumerate()
1078    {
1079        let absolute_run_end = absolute_run_end.as_usize();
1080        let end_in_slice = (absolute_run_end - array_offset).min(array_len);
1081
1082        if HAS_NULL_VALUES && sliced_values.is_null(adjusted_physical_index) {
1083            start_in_slice = end_in_slice;
1084            continue;
1085        }
1086
1087        let value_hash = values_hashes[adjusted_physical_index];
1088        let run_slice = &mut hashes_buffer[start_in_slice..end_in_slice];
1089
1090        if REHASH {
1091            for hash in run_slice.iter_mut() {
1092                *hash = combine_hashes(value_hash, *hash);
1093            }
1094        } else {
1095            run_slice.fill(value_hash);
1096        }
1097
1098        start_in_slice = end_in_slice;
1099    }
1100
1101    Ok(())
1102}
1103
1104#[cfg(not(feature = "force_hash_collisions"))]
1105fn hash_run_array<R: RunEndIndexType>(
1106    array: &RunArray<R>,
1107    child_hashing: &impl ChildHashing,
1108    hashes_buffer: &mut [u64],
1109    rehash: bool,
1110) -> Result<()> {
1111    let has_null_values = array.values().null_count() != 0;
1112
1113    match (has_null_values, rehash) {
1114        (false, false) => hash_run_array_inner::<R, _, false, false>(
1115            array,
1116            child_hashing,
1117            hashes_buffer,
1118        ),
1119        (false, true) => {
1120            hash_run_array_inner::<R, _, false, true>(array, child_hashing, hashes_buffer)
1121        }
1122        (true, false) => {
1123            hash_run_array_inner::<R, _, true, false>(array, child_hashing, hashes_buffer)
1124        }
1125        (true, true) => {
1126            hash_run_array_inner::<R, _, true, true>(array, child_hashing, hashes_buffer)
1127        }
1128    }
1129}
1130
1131/// Internal helper function that hashes a single array and either initializes or combines
1132/// the hash values in the buffer.
1133#[cfg(not(feature = "force_hash_collisions"))]
1134fn hash_single_array(
1135    array: &dyn Array,
1136    random_state: &impl HashState,
1137    hashes_buffer: &mut [u64],
1138    rehash: bool,
1139) -> Result<()> {
1140    downcast_primitive_array! {
1141        array => hash_array_primitive(array, random_state, hashes_buffer, rehash),
1142        DataType::Null => hash_null(random_state, hashes_buffer, rehash),
1143        DataType::Boolean => hash_array(&as_boolean_array(array)?, random_state, hashes_buffer, rehash),
1144        DataType::Utf8 => hash_array(&as_string_array(array)?, random_state, hashes_buffer, rehash),
1145        DataType::Utf8View => hash_generic_byte_view_array(as_string_view_array(array)?, random_state, hashes_buffer, rehash),
1146        DataType::LargeUtf8 => hash_array(&as_largestring_array(array), random_state, hashes_buffer, rehash),
1147        DataType::Binary => hash_array(&as_generic_binary_array::<i32>(array)?, random_state, hashes_buffer, rehash),
1148        DataType::BinaryView => hash_generic_byte_view_array(as_binary_view_array(array)?, random_state, hashes_buffer, rehash),
1149        DataType::LargeBinary => hash_array(&as_generic_binary_array::<i64>(array)?, random_state, hashes_buffer, rehash),
1150        DataType::FixedSizeBinary(_) => {
1151            let array: &FixedSizeBinaryArray = array.as_any().downcast_ref().unwrap();
1152            hash_array(&array, random_state, hashes_buffer, rehash)
1153        }
1154        DataType::Dictionary(_, _) => downcast_dictionary_array! {
1155            array => hash_dictionary(array, random_state, hashes_buffer, rehash)?,
1156            _ => unreachable!()
1157        }
1158        DataType::Struct(_) => {
1159            let array = as_struct_array(array)?;
1160            let child_hashing = HashStateChildHashing {
1161                hash_state: random_state,
1162            };
1163            hash_struct_array(array, &child_hashing, hashes_buffer)?;
1164        }
1165        DataType::List(_) => {
1166            let array = as_list_array(array)?;
1167            let child_hashing = HashStateChildHashing {
1168                hash_state: random_state,
1169            };
1170            hash_list_array(array, &child_hashing, hashes_buffer)?;
1171        }
1172        DataType::LargeList(_) => {
1173            let array = as_large_list_array(array)?;
1174            let child_hashing = HashStateChildHashing {
1175                hash_state: random_state,
1176            };
1177            hash_list_array(array, &child_hashing, hashes_buffer)?;
1178        }
1179        DataType::ListView(_) => {
1180            let array = as_list_view_array(array)?;
1181            let child_hashing = HashStateChildHashing {
1182                hash_state: random_state,
1183            };
1184            hash_list_view_array(array, &child_hashing, hashes_buffer)?;
1185        }
1186        DataType::LargeListView(_) => {
1187            let array = as_large_list_view_array(array)?;
1188            let child_hashing = HashStateChildHashing {
1189                hash_state: random_state,
1190            };
1191            hash_list_view_array(array, &child_hashing, hashes_buffer)?;
1192        }
1193        DataType::Map(_, _) => {
1194            let array = as_map_array(array)?;
1195            let child_hashing = HashStateChildHashing {
1196                hash_state: random_state,
1197            };
1198            hash_map_array(array, &child_hashing, hashes_buffer)?;
1199        }
1200        DataType::FixedSizeList(_,_) => {
1201            let array = as_fixed_size_list_array(array)?;
1202            let child_hashing = HashStateChildHashing {
1203                hash_state: random_state,
1204            };
1205            hash_fixed_list_array(array, &child_hashing, hashes_buffer)?;
1206        }
1207        DataType::Union(_, _) => {
1208            let array = as_union_array(array)?;
1209            let child_hashing = HashStateChildHashing {
1210                hash_state: random_state,
1211            };
1212            hash_union_array(array, &child_hashing, hashes_buffer)?;
1213        }
1214        DataType::RunEndEncoded(_, _) => downcast_run_array! {
1215            array => {
1216                let child_hashing = HashStateChildHashing {
1217                    hash_state: random_state,
1218                };
1219                hash_run_array(array, &child_hashing, hashes_buffer, rehash)?
1220            },
1221            _ => unreachable!()
1222        }
1223        _ => {
1224            // This is internal because we should have caught this before.
1225            return _internal_err!(
1226                "Unsupported data type in hasher: {}",
1227                array.data_type()
1228            );
1229        }
1230    }
1231    Ok(())
1232}
1233
1234/// Test version of `hash_single_array` that forces all hashes to collide to zero.
1235#[cfg(feature = "force_hash_collisions")]
1236fn hash_single_array(
1237    _array: &dyn Array,
1238    _random_state: &impl HashState,
1239    hashes_buffer: &mut [u64],
1240    _rehash: bool,
1241) -> Result<()> {
1242    for hash in hashes_buffer.iter_mut() {
1243        *hash = 0
1244    }
1245    Ok(())
1246}
1247
1248/// Something that can be returned as a `&dyn Array`.
1249///
1250/// We want `create_hashes` to accept either `&dyn Array` or `ArrayRef`,
1251/// and this seems the best way to do so.
1252///
1253/// We tried having it accept `AsRef<dyn Array>`
1254/// but that is not implemented for and cannot be implemented for
1255/// `&dyn Array` so callers that have the latter would not be able
1256/// to call `create_hashes` directly. This shim trait makes it possible.
1257pub trait AsDynArray {
1258    fn as_dyn_array(&self) -> &dyn Array;
1259}
1260
1261impl AsDynArray for dyn Array {
1262    fn as_dyn_array(&self) -> &dyn Array {
1263        self
1264    }
1265}
1266
1267impl AsDynArray for &dyn Array {
1268    fn as_dyn_array(&self) -> &dyn Array {
1269        *self
1270    }
1271}
1272
1273impl AsDynArray for ArrayRef {
1274    fn as_dyn_array(&self) -> &dyn Array {
1275        self.as_ref()
1276    }
1277}
1278
1279impl AsDynArray for &ArrayRef {
1280    fn as_dyn_array(&self) -> &dyn Array {
1281        self.as_ref()
1282    }
1283}
1284
1285/// Creates hash values for every row, based on the values in the columns.
1286///
1287/// The number of rows to hash is determined by `hashes_buffer.len()`.
1288/// `hashes_buffer` should be pre-sized appropriately.
1289pub fn create_hashes<'a, I, T>(
1290    arrays: I,
1291    random_state: &impl HashState,
1292    hashes_buffer: &'a mut [u64],
1293) -> Result<&'a mut [u64]>
1294where
1295    I: IntoIterator<Item = T>,
1296    T: AsDynArray,
1297{
1298    for (i, array) in arrays.into_iter().enumerate() {
1299        // combine hashes with `combine_hashes` for all columns besides the first
1300        let rehash = i >= 1;
1301        hash_single_array(array.as_dyn_array(), random_state, hashes_buffer, rehash)?;
1302    }
1303    Ok(hashes_buffer)
1304}
1305
1306/// Creates hash values for every row using a caller-provided hash builder.
1307///
1308/// The number of rows to hash is determined by `hashes_buffer.len()`.
1309/// `hashes_buffer` should be pre-sized appropriately.
1310///
1311/// # Hash compatibility
1312///
1313/// Hash values are not guaranteed to be bit-for-bit identical to those from
1314/// [`create_hashes`], even when `hash_builder` also implements [`HashState`].
1315/// The optimized [`HashState`] path seeds the hasher from the previous hash
1316/// when rehashing some primitive and byte-view values, whereas this function
1317/// combines independently computed hashes. Use one API consistently if hashes
1318/// are persisted or exchanged.
1319pub fn create_hashes_with_hasher<'a, I, T, S>(
1320    arrays: I,
1321    hash_builder: &S,
1322    hashes_buffer: &'a mut [u64],
1323) -> Result<&'a mut [u64]>
1324where
1325    I: IntoIterator<Item = T>,
1326    T: AsDynArray,
1327    S: BuildHasher,
1328{
1329    build_hasher::create_hashes_with_hasher(arrays, hash_builder, hashes_buffer)
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334    #[cfg(not(feature = "force_hash_collisions"))]
1335    use std::hash::{BuildHasherDefault, Hasher};
1336    use std::sync::Arc;
1337
1338    #[cfg(not(feature = "force_hash_collisions"))]
1339    use arrow::buffer::{NullBuffer, ScalarBuffer};
1340
1341    use super::*;
1342
1343    #[cfg(not(feature = "force_hash_collisions"))]
1344    #[derive(Default)]
1345    struct TestHasher(u64);
1346
1347    #[cfg(not(feature = "force_hash_collisions"))]
1348    impl Hasher for TestHasher {
1349        fn finish(&self) -> u64 {
1350            self.0
1351        }
1352
1353        fn write(&mut self, bytes: &[u8]) {
1354            for byte in bytes {
1355                self.0 = self.0.wrapping_mul(37).wrapping_add(u64::from(*byte));
1356            }
1357        }
1358    }
1359
1360    #[test]
1361    fn create_hashes_for_decimal_array() -> Result<()> {
1362        let array = vec![1, 2, 3, 4]
1363            .into_iter()
1364            .map(Some)
1365            .collect::<Decimal128Array>()
1366            .with_precision_and_scale(20, 3)
1367            .unwrap();
1368        let array_ref: ArrayRef = Arc::new(array);
1369        let random_state = RandomState::with_seed(0);
1370        let hashes_buff = &mut vec![0; array_ref.len()];
1371        let hashes = create_hashes(&[array_ref], &random_state, hashes_buff)?;
1372        assert_eq!(hashes.len(), 4);
1373        Ok(())
1374    }
1375
1376    #[test]
1377    fn create_hashes_for_empty_fixed_size_lit() -> Result<()> {
1378        let empty_array = FixedSizeListBuilder::new(StringBuilder::new(), 1).finish();
1379        let random_state = RandomState::with_seed(0);
1380        let hashes_buff = &mut [0; 0];
1381        let hashes = create_hashes(
1382            &[Arc::new(empty_array) as ArrayRef],
1383            &random_state,
1384            hashes_buff,
1385        )?;
1386        assert_eq!(hashes, &Vec::<u64>::new());
1387        Ok(())
1388    }
1389
1390    #[test]
1391    fn create_hashes_for_float_arrays() -> Result<()> {
1392        let f32_arr: ArrayRef =
1393            Arc::new(Float32Array::from(vec![0.12, 0.5, 1f32, 444.7]));
1394        let f64_arr: ArrayRef =
1395            Arc::new(Float64Array::from(vec![0.12, 0.5, 1f64, 444.7]));
1396
1397        let random_state = RandomState::with_seed(0);
1398        let hashes_buff = &mut vec![0; f32_arr.len()];
1399        let hashes = create_hashes(&[f32_arr], &random_state, hashes_buff)?;
1400        assert_eq!(hashes.len(), 4,);
1401
1402        let hashes = create_hashes(&[f64_arr], &random_state, hashes_buff)?;
1403        assert_eq!(hashes.len(), 4,);
1404
1405        Ok(())
1406    }
1407
1408    macro_rules! create_hash_binary {
1409        ($NAME:ident, $ARRAY:ty) => {
1410            #[cfg(not(feature = "force_hash_collisions"))]
1411            #[test]
1412            fn $NAME() {
1413                let binary = [
1414                    Some(b"short".to_byte_slice()),
1415                    None,
1416                    Some(b"long but different 12 bytes string"),
1417                    Some(b"short2"),
1418                    Some(b"Longer than 12 bytes string"),
1419                    Some(b"short"),
1420                    Some(b"Longer than 12 bytes string"),
1421                ];
1422
1423                let binary_array: ArrayRef =
1424                    Arc::new(binary.iter().cloned().collect::<$ARRAY>());
1425
1426                let random_state = RandomState::with_seed(0);
1427
1428                let mut binary_hashes = vec![0; binary.len()];
1429                create_hashes(&[binary_array], &random_state, &mut binary_hashes)
1430                    .unwrap();
1431
1432                // Null values result in a zero hash,
1433                for (val, hash) in binary.iter().zip(binary_hashes.iter()) {
1434                    match val {
1435                        Some(_) => assert_ne!(*hash, 0),
1436                        None => assert_eq!(*hash, 0),
1437                    }
1438                }
1439
1440                // Same values should map to same hash values
1441                assert_eq!(binary[0], binary[5]);
1442                assert_eq!(binary[4], binary[6]);
1443
1444                // different binary should map to different hash values
1445                assert_ne!(binary[0], binary[2]);
1446            }
1447        };
1448    }
1449
1450    create_hash_binary!(binary_array, BinaryArray);
1451    create_hash_binary!(large_binary_array, LargeBinaryArray);
1452    create_hash_binary!(binary_view_array, BinaryViewArray);
1453
1454    #[test]
1455    fn create_hashes_fixed_size_binary() -> Result<()> {
1456        let input_arg = vec![vec![1, 2], vec![5, 6], vec![5, 6]];
1457        let fixed_size_binary_array: ArrayRef =
1458            Arc::new(FixedSizeBinaryArray::try_from_iter(input_arg.into_iter()).unwrap());
1459
1460        let random_state = RandomState::with_seed(0);
1461        let hashes_buff = &mut vec![0; fixed_size_binary_array.len()];
1462        let hashes =
1463            create_hashes(&[fixed_size_binary_array], &random_state, hashes_buff)?;
1464        assert_eq!(hashes.len(), 3,);
1465
1466        Ok(())
1467    }
1468
1469    macro_rules! create_hash_string {
1470        ($NAME:ident, $ARRAY:ty) => {
1471            #[cfg(not(feature = "force_hash_collisions"))]
1472            #[test]
1473            fn $NAME() {
1474                let strings = [
1475                    Some("short"),
1476                    None,
1477                    Some("long but different 12 bytes string"),
1478                    Some("short2"),
1479                    Some("Longer than 12 bytes string"),
1480                    Some("short"),
1481                    Some("Longer than 12 bytes string"),
1482                ];
1483
1484                let string_array: ArrayRef =
1485                    Arc::new(strings.iter().cloned().collect::<$ARRAY>());
1486                let dict_array: ArrayRef = Arc::new(
1487                    strings
1488                        .iter()
1489                        .cloned()
1490                        .collect::<DictionaryArray<Int8Type>>(),
1491                );
1492
1493                let random_state = RandomState::with_seed(0);
1494
1495                let mut string_hashes = vec![0; strings.len()];
1496                create_hashes(&[string_array], &random_state, &mut string_hashes)
1497                    .unwrap();
1498
1499                let mut dict_hashes = vec![0; strings.len()];
1500                create_hashes(&[dict_array], &random_state, &mut dict_hashes).unwrap();
1501
1502                // Null values result in a zero hash,
1503                for (val, hash) in strings.iter().zip(string_hashes.iter()) {
1504                    match val {
1505                        Some(_) => assert_ne!(*hash, 0),
1506                        None => assert_eq!(*hash, 0),
1507                    }
1508                }
1509
1510                // same logical values should hash to the same hash value
1511                assert_eq!(string_hashes, dict_hashes);
1512
1513                // Same values should map to same hash values
1514                assert_eq!(strings[0], strings[5]);
1515                assert_eq!(strings[4], strings[6]);
1516
1517                // different strings should map to different hash values
1518                assert_ne!(strings[0], strings[2]);
1519            }
1520        };
1521    }
1522
1523    create_hash_string!(string_array, StringArray);
1524    create_hash_string!(large_string_array, LargeStringArray);
1525    create_hash_string!(string_view_array, StringArray);
1526    create_hash_string!(dict_string_array, DictionaryArray<Int8Type>);
1527
1528    #[test]
1529    #[cfg(not(feature = "force_hash_collisions"))]
1530    fn create_hashes_for_run_array() -> Result<()> {
1531        let values = Arc::new(Int32Array::from(vec![10, 20, 30]));
1532        let run_ends = Arc::new(Int32Array::from(vec![2, 5, 7]));
1533        let array = Arc::new(RunArray::try_new(&run_ends, values.as_ref()).unwrap());
1534
1535        let random_state = RandomState::with_seed(0);
1536        let hashes_buff = &mut vec![0; array.len()];
1537        let hashes = create_hashes(
1538            &[Arc::clone(&array) as ArrayRef],
1539            &random_state,
1540            hashes_buff,
1541        )?;
1542
1543        assert_eq!(hashes.len(), 7);
1544        assert_eq!(hashes[0], hashes[1]);
1545        assert_eq!(hashes[2], hashes[3]);
1546        assert_eq!(hashes[3], hashes[4]);
1547        assert_eq!(hashes[5], hashes[6]);
1548        assert_ne!(hashes[0], hashes[2]);
1549        assert_ne!(hashes[2], hashes[5]);
1550        assert_ne!(hashes[0], hashes[5]);
1551
1552        Ok(())
1553    }
1554
1555    #[test]
1556    #[cfg(not(feature = "force_hash_collisions"))]
1557    fn create_multi_column_hash_with_run_array() -> Result<()> {
1558        let int_array = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7]));
1559        let values = Arc::new(StringArray::from(vec!["foo", "bar", "baz"]));
1560        let run_ends = Arc::new(Int32Array::from(vec![2, 5, 7]));
1561        let run_array = Arc::new(RunArray::try_new(&run_ends, values.as_ref()).unwrap());
1562
1563        let random_state = RandomState::with_seed(0);
1564        let mut one_col_hashes = vec![0; int_array.len()];
1565        create_hashes(
1566            &[Arc::clone(&int_array) as ArrayRef],
1567            &random_state,
1568            &mut one_col_hashes,
1569        )?;
1570
1571        let mut two_col_hashes = vec![0; int_array.len()];
1572        create_hashes(
1573            &[
1574                Arc::clone(&int_array) as ArrayRef,
1575                Arc::clone(&run_array) as ArrayRef,
1576            ],
1577            &random_state,
1578            &mut two_col_hashes,
1579        )?;
1580
1581        assert_eq!(one_col_hashes.len(), 7);
1582        assert_eq!(two_col_hashes.len(), 7);
1583        assert_ne!(one_col_hashes, two_col_hashes);
1584
1585        let diff_0_vs_1_one_col = one_col_hashes[0] != one_col_hashes[1];
1586        let diff_0_vs_1_two_col = two_col_hashes[0] != two_col_hashes[1];
1587        assert_eq!(diff_0_vs_1_one_col, diff_0_vs_1_two_col);
1588
1589        let diff_2_vs_3_one_col = one_col_hashes[2] != one_col_hashes[3];
1590        let diff_2_vs_3_two_col = two_col_hashes[2] != two_col_hashes[3];
1591        assert_eq!(diff_2_vs_3_one_col, diff_2_vs_3_two_col);
1592
1593        Ok(())
1594    }
1595
1596    #[test]
1597    #[cfg(not(feature = "force_hash_collisions"))]
1598    fn test_create_hashes_with_custom_hasher() {
1599        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 1, 4]));
1600        let hash_builder = BuildHasherDefault::<TestHasher>::default();
1601
1602        let mut custom_hashes = vec![0; array.len()];
1603        create_hashes_with_hasher([&array], &hash_builder, &mut custom_hashes).unwrap();
1604
1605        let random_state = RandomState::with_seed(0);
1606        let mut default_hashes = vec![0; array.len()];
1607        create_hashes([&array], &random_state, &mut default_hashes).unwrap();
1608
1609        assert_eq!(custom_hashes[0], custom_hashes[2]);
1610        assert_ne!(custom_hashes[0], custom_hashes[1]);
1611        assert_ne!(custom_hashes, default_hashes);
1612    }
1613
1614    #[test]
1615    #[cfg(not(feature = "force_hash_collisions"))]
1616    fn test_create_hashes_with_custom_hasher_normalizes_negative_zero() {
1617        let array: ArrayRef = Arc::new(Float64Array::from(vec![0.0, -0.0]));
1618        let hash_builder = BuildHasherDefault::<TestHasher>::default();
1619        let mut hashes = vec![0; array.len()];
1620
1621        create_hashes_with_hasher([&array], &hash_builder, &mut hashes).unwrap();
1622
1623        assert_eq!(hashes[0], hashes[1]);
1624    }
1625
1626    #[test]
1627    #[cfg(not(feature = "force_hash_collisions"))]
1628    fn test_create_hashes_dictionary_with_custom_hasher() {
1629        let strings = [Some("foo"), None, Some("bar"), Some("foo"), None];
1630        let string_array: ArrayRef =
1631            Arc::new(strings.iter().copied().collect::<StringArray>());
1632        let dict_array: ArrayRef = Arc::new(
1633            strings
1634                .iter()
1635                .copied()
1636                .collect::<DictionaryArray<Int8Type>>(),
1637        );
1638        let hash_builder = BuildHasherDefault::<TestHasher>::default();
1639
1640        let mut string_hashes = vec![0; strings.len()];
1641        create_hashes_with_hasher([&string_array], &hash_builder, &mut string_hashes)
1642            .unwrap();
1643
1644        let mut dict_hashes = vec![0; strings.len()];
1645        create_hashes_with_hasher([&dict_array], &hash_builder, &mut dict_hashes)
1646            .unwrap();
1647
1648        assert_eq!(string_hashes, dict_hashes);
1649    }
1650
1651    #[test]
1652    #[cfg(not(feature = "force_hash_collisions"))]
1653    fn test_create_hashes_struct_with_custom_hasher() {
1654        let struct_array = StructArray::from(vec![
1655            (
1656                Arc::new(Field::new("int", DataType::Int32, false)),
1657                Arc::new(Int32Array::from(vec![1, 2, 1, 3])) as ArrayRef,
1658            ),
1659            (
1660                Arc::new(Field::new("string", DataType::Utf8, false)),
1661                Arc::new(StringArray::from(vec!["alpha", "beta", "alpha", "alpha"]))
1662                    as ArrayRef,
1663            ),
1664        ]);
1665        let hash_builder = BuildHasherDefault::<TestHasher>::default();
1666
1667        let mut child_hashes = vec![0; struct_array.len()];
1668        create_hashes_with_hasher(
1669            struct_array.columns(),
1670            &hash_builder,
1671            &mut child_hashes,
1672        )
1673        .unwrap();
1674        let expected_hashes = child_hashes
1675            .into_iter()
1676            .map(|hash| combine_hashes(0, hash))
1677            .collect::<Vec<_>>();
1678
1679        let array: ArrayRef = Arc::new(struct_array);
1680        let mut actual_hashes = vec![0; array.len()];
1681        create_hashes_with_hasher([&array], &hash_builder, &mut actual_hashes).unwrap();
1682
1683        assert_eq!(actual_hashes, expected_hashes);
1684        assert_eq!(actual_hashes[0], actual_hashes[2]);
1685        assert_ne!(actual_hashes[0], actual_hashes[3]);
1686    }
1687
1688    #[test]
1689    #[cfg(not(feature = "force_hash_collisions"))]
1690    fn test_create_hashes_long_utf8_view_with_custom_hasher() {
1691        let values = vec![
1692            Some("this string is longer than twelve bytes"),
1693            None,
1694            Some("another string longer than twelve bytes"),
1695            Some("this string is longer than twelve bytes"),
1696        ];
1697        let view_array = StringViewArray::from(values.clone());
1698        assert!(!view_array.data_buffers().is_empty());
1699        let view_array: ArrayRef = Arc::new(view_array);
1700        let hash_builder = BuildHasherDefault::<TestHasher>::default();
1701
1702        let mut view_hashes = vec![0; view_array.len()];
1703        create_hashes_with_hasher([&view_array], &hash_builder, &mut view_hashes)
1704            .unwrap();
1705        let expected_hashes = values
1706            .iter()
1707            .map(|value| {
1708                value
1709                    .map(|value| hash_builder.hash_one(value.as_bytes()))
1710                    .unwrap_or_default()
1711            })
1712            .collect::<Vec<_>>();
1713        assert_eq!(view_hashes, expected_hashes);
1714
1715        let prefix_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 1]));
1716        let mut expected_hashes = vec![0; prefix_array.len()];
1717        create_hashes_with_hasher([&prefix_array], &hash_builder, &mut expected_hashes)
1718            .unwrap();
1719        for (hash, value) in expected_hashes.iter_mut().zip(&values) {
1720            if let Some(value) = value {
1721                *hash = combine_hashes(hash_builder.hash_one(value.as_bytes()), *hash);
1722            }
1723        }
1724
1725        let mut view_hashes = vec![0; view_array.len()];
1726        create_hashes_with_hasher(
1727            [&prefix_array, &view_array],
1728            &hash_builder,
1729            &mut view_hashes,
1730        )
1731        .unwrap();
1732        assert_eq!(view_hashes, expected_hashes);
1733    }
1734
1735    #[test]
1736    #[cfg(not(feature = "force_hash_collisions"))]
1737    fn test_single_column_leaf_hashes_match_with_same_hasher() {
1738        let arrays: Vec<ArrayRef> = vec![
1739            Arc::new(Int32Array::from(vec![Some(1), None, Some(-1)])),
1740            Arc::new(Float64Array::from(vec![Some(0.0), Some(-0.0), None])),
1741            Arc::new(StringArray::from(vec![Some("foo"), None, Some("bar")])),
1742            Arc::new(BinaryArray::from(vec![
1743                Some(&b"short"[..]),
1744                None,
1745                Some(&b"longer than twelve bytes"[..]),
1746            ])),
1747            Arc::new(StringViewArray::from(vec![
1748                Some("short"),
1749                None,
1750                Some("longer than twelve bytes"),
1751            ])),
1752        ];
1753        let random_state = RandomState::with_seed(0);
1754
1755        for array in arrays {
1756            let mut default_hashes = vec![0; array.len()];
1757            create_hashes([&array], &random_state, &mut default_hashes).unwrap();
1758
1759            let mut custom_hashes = vec![0; array.len()];
1760            create_hashes_with_hasher([&array], &random_state, &mut custom_hashes)
1761                .unwrap();
1762
1763            assert_eq!(
1764                custom_hashes,
1765                default_hashes,
1766                "single-column parity failed for {}",
1767                array.data_type()
1768            );
1769        }
1770    }
1771
1772    #[test]
1773    #[cfg(not(feature = "force_hash_collisions"))]
1774    fn test_with_hashes_with_custom_hasher() {
1775        let int_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1776        let str_array: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c"]));
1777        let hash_builder = BuildHasherDefault::<TestHasher>::default();
1778
1779        let mut expected_hashes = vec![0; int_array.len()];
1780        create_hashes_with_hasher(
1781            [&int_array, &str_array],
1782            &hash_builder,
1783            &mut expected_hashes,
1784        )
1785        .unwrap();
1786
1787        let actual_hashes =
1788            with_hashes_with_hasher([&int_array, &str_array], &hash_builder, |hashes| {
1789                Ok(hashes.to_vec())
1790            })
1791            .unwrap();
1792
1793        assert_eq!(actual_hashes, expected_hashes);
1794    }
1795
1796    #[test]
1797    // Tests actual values of hashes, which are different if forcing collisions
1798    #[cfg(not(feature = "force_hash_collisions"))]
1799    fn create_hashes_for_dict_arrays() {
1800        let strings = [Some("foo"), None, Some("bar"), Some("foo"), None];
1801
1802        let string_array: ArrayRef =
1803            Arc::new(strings.iter().copied().collect::<StringArray>());
1804        let dict_array: ArrayRef = Arc::new(
1805            strings
1806                .iter()
1807                .copied()
1808                .collect::<DictionaryArray<Int8Type>>(),
1809        );
1810
1811        let random_state = RandomState::with_seed(0);
1812
1813        let mut string_hashes = vec![0; strings.len()];
1814        create_hashes(&[string_array], &random_state, &mut string_hashes).unwrap();
1815
1816        let mut dict_hashes = vec![0; strings.len()];
1817        create_hashes(&[dict_array], &random_state, &mut dict_hashes).unwrap();
1818
1819        // Null values result in a zero hash,
1820        for (val, hash) in strings.iter().zip(string_hashes.iter()) {
1821            match val {
1822                Some(_) => assert_ne!(*hash, 0),
1823                None => assert_eq!(*hash, 0),
1824            }
1825        }
1826
1827        // same logical values should hash to the same hash value
1828        assert_eq!(string_hashes, dict_hashes);
1829
1830        // Same values should map to same hash values
1831        assert_eq!(strings[1], strings[4]);
1832        assert_eq!(dict_hashes[1], dict_hashes[4]);
1833        assert_eq!(strings[0], strings[3]);
1834        assert_eq!(dict_hashes[0], dict_hashes[3]);
1835
1836        // different strings should map to different hash values
1837        assert_ne!(strings[0], strings[2]);
1838        assert_ne!(dict_hashes[0], dict_hashes[2]);
1839    }
1840
1841    #[test]
1842    // Tests actual values of hashes, which are different if forcing collisions
1843    #[cfg(not(feature = "force_hash_collisions"))]
1844    fn create_hashes_for_list_arrays() {
1845        let data = vec![
1846            Some(vec![Some(0), Some(1), Some(2)]),
1847            None,
1848            Some(vec![Some(3), None, Some(5)]),
1849            Some(vec![Some(3), None, Some(5)]),
1850            None,
1851            Some(vec![Some(0), Some(1), Some(2)]),
1852            Some(vec![]),
1853        ];
1854        let list_array =
1855            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(data)) as ArrayRef;
1856        let random_state = RandomState::with_seed(0);
1857        let mut hashes = vec![0; list_array.len()];
1858        create_hashes(&[list_array], &random_state, &mut hashes).unwrap();
1859        assert_eq!(hashes[0], hashes[5]);
1860        assert_eq!(hashes[1], hashes[4]);
1861        assert_eq!(hashes[2], hashes[3]);
1862        assert_eq!(hashes[1], hashes[6]); // null vs empty list
1863    }
1864
1865    #[test]
1866    #[cfg(not(feature = "force_hash_collisions"))]
1867    fn create_hashes_for_sliced_list_arrays() {
1868        let data = vec![
1869            Some(vec![Some(0), Some(1), Some(2)]),
1870            None,
1871            // Slice from here
1872            Some(vec![Some(3), None, Some(5)]),
1873            Some(vec![Some(3), None, Some(5)]),
1874            None,
1875            // To here
1876            Some(vec![Some(0), Some(1), Some(2)]),
1877            Some(vec![]),
1878        ];
1879        let list_array =
1880            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(data)) as ArrayRef;
1881        let list_array = list_array.slice(2, 3);
1882        let random_state = RandomState::with_seed(0);
1883        let mut hashes = vec![0; list_array.len()];
1884        create_hashes(&[list_array], &random_state, &mut hashes).unwrap();
1885        assert_eq!(hashes[0], hashes[1]);
1886        assert_ne!(hashes[1], hashes[2]);
1887    }
1888
1889    #[test]
1890    // Tests actual values of hashes, which are different if forcing collisions
1891    #[cfg(not(feature = "force_hash_collisions"))]
1892    fn create_hashes_for_list_view_arrays() {
1893        // Create values array: [0, 1, 2, 3, null, 5]
1894        let values = Arc::new(Int32Array::from(vec![
1895            Some(0),
1896            Some(1),
1897            Some(2),
1898            Some(3),
1899            None,
1900            Some(5),
1901        ])) as ArrayRef;
1902        let field = Arc::new(Field::new("item", DataType::Int32, true));
1903
1904        // Create ListView with the following logical structure:
1905        // Row 0: [0, 1, 2]        (offset=0, size=3)
1906        // Row 1: null             (null bit set)
1907        // Row 2: [3, null, 5]     (offset=3, size=3)
1908        // Row 3: [3, null, 5]     (offset=3, size=3) - same as row 2
1909        // Row 4: null             (null bit set)
1910        // Row 5: [0, 1, 2]        (offset=0, size=3) - same as row 0
1911        // Row 6: []               (offset=0, size=0) - empty list
1912        let offsets = ScalarBuffer::from(vec![0i32, 0, 3, 3, 0, 0, 0]);
1913        let sizes = ScalarBuffer::from(vec![3i32, 0, 3, 3, 0, 3, 0]);
1914        let nulls = Some(NullBuffer::from(vec![
1915            true, false, true, true, false, true, true,
1916        ]));
1917
1918        let list_view_array =
1919            Arc::new(ListViewArray::new(field, offsets, sizes, values, nulls))
1920                as ArrayRef;
1921
1922        let random_state = RandomState::with_seed(0);
1923        let mut hashes = vec![0; list_view_array.len()];
1924        create_hashes(&[list_view_array], &random_state, &mut hashes).unwrap();
1925
1926        assert_eq!(hashes[0], hashes[5]); // same content [0, 1, 2]
1927        assert_eq!(hashes[1], hashes[4]); // both null
1928        assert_eq!(hashes[2], hashes[3]); // same content [3, null, 5]
1929        assert_eq!(hashes[1], hashes[6]); // null vs empty list
1930
1931        // Negative tests: different content should produce different hashes
1932        assert_ne!(hashes[0], hashes[2]); // [0, 1, 2] vs [3, null, 5]
1933        assert_ne!(hashes[0], hashes[6]); // [0, 1, 2] vs []
1934        assert_ne!(hashes[2], hashes[6]); // [3, null, 5] vs []
1935    }
1936
1937    #[test]
1938    // Tests actual values of hashes, which are different if forcing collisions
1939    #[cfg(not(feature = "force_hash_collisions"))]
1940    fn create_hashes_for_large_list_view_arrays() {
1941        // Create values array: [0, 1, 2, 3, null, 5]
1942        let values = Arc::new(Int32Array::from(vec![
1943            Some(0),
1944            Some(1),
1945            Some(2),
1946            Some(3),
1947            None,
1948            Some(5),
1949        ])) as ArrayRef;
1950        let field = Arc::new(Field::new("item", DataType::Int32, true));
1951
1952        // Create LargeListView with the following logical structure:
1953        // Row 0: [0, 1, 2]        (offset=0, size=3)
1954        // Row 1: null             (null bit set)
1955        // Row 2: [3, null, 5]     (offset=3, size=3)
1956        // Row 3: [3, null, 5]     (offset=3, size=3) - same as row 2
1957        // Row 4: null             (null bit set)
1958        // Row 5: [0, 1, 2]        (offset=0, size=3) - same as row 0
1959        // Row 6: []               (offset=0, size=0) - empty list
1960        let offsets = ScalarBuffer::from(vec![0i64, 0, 3, 3, 0, 0, 0]);
1961        let sizes = ScalarBuffer::from(vec![3i64, 0, 3, 3, 0, 3, 0]);
1962        let nulls = Some(NullBuffer::from(vec![
1963            true, false, true, true, false, true, true,
1964        ]));
1965
1966        let large_list_view_array = Arc::new(LargeListViewArray::new(
1967            field, offsets, sizes, values, nulls,
1968        )) as ArrayRef;
1969
1970        let random_state = RandomState::with_seed(0);
1971        let mut hashes = vec![0; large_list_view_array.len()];
1972        create_hashes(&[large_list_view_array], &random_state, &mut hashes).unwrap();
1973
1974        assert_eq!(hashes[0], hashes[5]); // same content [0, 1, 2]
1975        assert_eq!(hashes[1], hashes[4]); // both null
1976        assert_eq!(hashes[2], hashes[3]); // same content [3, null, 5]
1977        assert_eq!(hashes[1], hashes[6]); // null vs empty list
1978
1979        // Negative tests: different content should produce different hashes
1980        assert_ne!(hashes[0], hashes[2]); // [0, 1, 2] vs [3, null, 5]
1981        assert_ne!(hashes[0], hashes[6]); // [0, 1, 2] vs []
1982        assert_ne!(hashes[2], hashes[6]); // [3, null, 5] vs []
1983    }
1984
1985    #[test]
1986    // Tests actual values of hashes, which are different if forcing collisions
1987    #[cfg(not(feature = "force_hash_collisions"))]
1988    fn create_hashes_for_fixed_size_list_arrays() {
1989        let data = vec![
1990            Some(vec![Some(0), Some(1), Some(2)]),
1991            None,
1992            Some(vec![Some(3), None, Some(5)]),
1993            Some(vec![Some(3), None, Some(5)]),
1994            None,
1995            Some(vec![Some(0), Some(1), Some(2)]),
1996        ];
1997        let list_array =
1998            Arc::new(FixedSizeListArray::from_iter_primitive::<Int32Type, _, _>(
1999                data, 3,
2000            )) as ArrayRef;
2001        let random_state = RandomState::with_seed(0);
2002        let mut hashes = vec![0; list_array.len()];
2003        create_hashes(&[list_array], &random_state, &mut hashes).unwrap();
2004        assert_eq!(hashes[0], hashes[5]);
2005        assert_eq!(hashes[1], hashes[4]);
2006        assert_eq!(hashes[2], hashes[3]);
2007    }
2008
2009    #[test]
2010    // Tests actual values of hashes, which are different if forcing collisions
2011    #[cfg(not(feature = "force_hash_collisions"))]
2012    fn create_hashes_for_struct_arrays() {
2013        use arrow::buffer::Buffer;
2014
2015        let boolarr = Arc::new(BooleanArray::from(vec![
2016            false, false, true, true, true, true,
2017        ]));
2018        let i32arr = Arc::new(Int32Array::from(vec![10, 10, 20, 20, 30, 31]));
2019
2020        let struct_array = StructArray::from((
2021            vec![
2022                (
2023                    Arc::new(Field::new("bool", DataType::Boolean, false)),
2024                    Arc::clone(&boolarr) as ArrayRef,
2025                ),
2026                (
2027                    Arc::new(Field::new("i32", DataType::Int32, false)),
2028                    Arc::clone(&i32arr) as ArrayRef,
2029                ),
2030                (
2031                    Arc::new(Field::new("i32", DataType::Int32, false)),
2032                    Arc::clone(&i32arr) as ArrayRef,
2033                ),
2034                (
2035                    Arc::new(Field::new("bool", DataType::Boolean, false)),
2036                    Arc::clone(&boolarr) as ArrayRef,
2037                ),
2038            ],
2039            Buffer::from(&[0b001011]),
2040        ));
2041
2042        assert!(struct_array.is_valid(0));
2043        assert!(struct_array.is_valid(1));
2044        assert!(struct_array.is_null(2));
2045        assert!(struct_array.is_valid(3));
2046        assert!(struct_array.is_null(4));
2047        assert!(struct_array.is_null(5));
2048
2049        let array = Arc::new(struct_array) as ArrayRef;
2050
2051        let random_state = RandomState::with_seed(0);
2052        let mut hashes = vec![0; array.len()];
2053        create_hashes(&[array], &random_state, &mut hashes).unwrap();
2054        assert_eq!(hashes[0], hashes[1]);
2055        // same value but the third row ( hashes[2] ) is null
2056        assert_ne!(hashes[2], hashes[3]);
2057        // different values but both are null
2058        assert_eq!(hashes[4], hashes[5]);
2059    }
2060
2061    #[test]
2062    // Tests actual values of hashes, which are different if forcing collisions
2063    #[cfg(not(feature = "force_hash_collisions"))]
2064    fn create_hashes_for_struct_arrays_more_column_than_row() {
2065        let struct_array = StructArray::from(vec![
2066            (
2067                Arc::new(Field::new("bool", DataType::Boolean, false)),
2068                Arc::new(BooleanArray::from(vec![false, false])) as ArrayRef,
2069            ),
2070            (
2071                Arc::new(Field::new("i32-1", DataType::Int32, false)),
2072                Arc::new(Int32Array::from(vec![10, 10])) as ArrayRef,
2073            ),
2074            (
2075                Arc::new(Field::new("i32-2", DataType::Int32, false)),
2076                Arc::new(Int32Array::from(vec![10, 10])) as ArrayRef,
2077            ),
2078            (
2079                Arc::new(Field::new("i32-3", DataType::Int32, false)),
2080                Arc::new(Int32Array::from(vec![10, 10])) as ArrayRef,
2081            ),
2082        ]);
2083
2084        assert!(struct_array.is_valid(0));
2085        assert!(struct_array.is_valid(1));
2086
2087        let array = Arc::new(struct_array) as ArrayRef;
2088        let random_state = RandomState::with_seed(0);
2089        let mut hashes = vec![0; array.len()];
2090        create_hashes(&[array], &random_state, &mut hashes).unwrap();
2091        assert_eq!(hashes[0], hashes[1]);
2092    }
2093
2094    #[test]
2095    // Tests actual values of hashes, which are different if forcing collisions
2096    #[cfg(not(feature = "force_hash_collisions"))]
2097    fn create_hashes_for_map_arrays() {
2098        let mut builder =
2099            MapBuilder::new(None, StringBuilder::new(), Int32Builder::new());
2100        // Row 0
2101        builder.keys().append_value("key1");
2102        builder.keys().append_value("key2");
2103        builder.values().append_value(1);
2104        builder.values().append_value(2);
2105        builder.append(true).unwrap();
2106        // Row 1
2107        builder.keys().append_value("key1");
2108        builder.keys().append_value("key2");
2109        builder.values().append_value(1);
2110        builder.values().append_value(2);
2111        builder.append(true).unwrap();
2112        // Row 2
2113        builder.keys().append_value("key1");
2114        builder.keys().append_value("key2");
2115        builder.values().append_value(1);
2116        builder.values().append_value(3);
2117        builder.append(true).unwrap();
2118        // Row 3
2119        builder.keys().append_value("key1");
2120        builder.keys().append_value("key3");
2121        builder.values().append_value(1);
2122        builder.values().append_value(2);
2123        builder.append(true).unwrap();
2124        // Row 4
2125        builder.keys().append_value("key1");
2126        builder.values().append_value(1);
2127        builder.append(true).unwrap();
2128        // Row 5
2129        builder.keys().append_value("key1");
2130        builder.values().append_null();
2131        builder.append(true).unwrap();
2132        // Row 6
2133        builder.append(true).unwrap();
2134        // Row 7
2135        builder.keys().append_value("key1");
2136        builder.values().append_value(1);
2137        builder.append(false).unwrap();
2138
2139        let array = Arc::new(builder.finish()) as ArrayRef;
2140
2141        let random_state = RandomState::with_seed(0);
2142        let mut hashes = vec![0; array.len()];
2143        create_hashes(&[array], &random_state, &mut hashes).unwrap();
2144        assert_eq!(hashes[0], hashes[1]); // same value
2145        assert_ne!(hashes[0], hashes[2]); // different value
2146        assert_ne!(hashes[0], hashes[3]); // different key
2147        assert_ne!(hashes[0], hashes[4]); // missing an entry
2148        assert_ne!(hashes[4], hashes[5]); // filled vs null value
2149        assert_eq!(hashes[6], hashes[7]); // empty vs null map
2150    }
2151
2152    #[test]
2153    // Tests actual values of hashes, which are different if forcing collisions
2154    #[cfg(not(feature = "force_hash_collisions"))]
2155    fn create_multi_column_hash_for_dict_arrays() {
2156        let strings1 = [Some("foo"), None, Some("bar")];
2157        let strings2 = [Some("blarg"), Some("blah"), None];
2158
2159        let string_array: ArrayRef =
2160            Arc::new(strings1.iter().copied().collect::<StringArray>());
2161        let dict_array: ArrayRef = Arc::new(
2162            strings2
2163                .iter()
2164                .copied()
2165                .collect::<DictionaryArray<Int32Type>>(),
2166        );
2167
2168        let random_state = RandomState::with_seed(0);
2169
2170        let mut one_col_hashes = vec![0; strings1.len()];
2171        create_hashes(
2172            &[Arc::clone(&dict_array) as ArrayRef],
2173            &random_state,
2174            &mut one_col_hashes,
2175        )
2176        .unwrap();
2177
2178        let mut two_col_hashes = vec![0; strings1.len()];
2179        create_hashes(
2180            &[dict_array, string_array],
2181            &random_state,
2182            &mut two_col_hashes,
2183        )
2184        .unwrap();
2185
2186        assert_eq!(one_col_hashes.len(), 3);
2187        assert_eq!(two_col_hashes.len(), 3);
2188
2189        assert_ne!(one_col_hashes, two_col_hashes);
2190    }
2191
2192    #[test]
2193    fn test_create_hashes_from_arrays() {
2194        let int_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2195        let float_array: ArrayRef =
2196            Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0]));
2197
2198        let random_state = RandomState::with_seed(0);
2199        let hashes_buff = &mut vec![0; int_array.len()];
2200        let hashes =
2201            create_hashes(&[int_array, float_array], &random_state, hashes_buff).unwrap();
2202        assert_eq!(hashes.len(), 4,);
2203    }
2204
2205    #[test]
2206    fn test_create_hashes_from_dyn_arrays() {
2207        let int_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2208        let float_array: ArrayRef =
2209            Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0]));
2210
2211        // Verify that we can call create_hashes with only &dyn Array
2212        fn test(arr1: &dyn Array, arr2: &dyn Array) {
2213            let random_state = RandomState::with_seed(0);
2214            let hashes_buff = &mut vec![0; arr1.len()];
2215            let hashes = create_hashes([arr1, arr2], &random_state, hashes_buff).unwrap();
2216            assert_eq!(hashes.len(), 4,);
2217        }
2218        test(&*int_array, &*float_array);
2219    }
2220
2221    #[test]
2222    fn test_create_hashes_equivalence() {
2223        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2224        let random_state = RandomState::with_seed(0);
2225
2226        let mut hashes1 = vec![0; array.len()];
2227        create_hashes(
2228            &[Arc::clone(&array) as ArrayRef],
2229            &random_state,
2230            &mut hashes1,
2231        )
2232        .unwrap();
2233
2234        let mut hashes2 = vec![0; array.len()];
2235        create_hashes([array], &random_state, &mut hashes2).unwrap();
2236
2237        assert_eq!(hashes1, hashes2);
2238    }
2239
2240    #[test]
2241    #[cfg(not(feature = "force_hash_collisions"))]
2242    fn test_create_hashes_with_quality_hash_state() {
2243        let int_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2244        let str_array: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c", "d"]));
2245        let quality_state = foldhash::quality::FixedState::with_seed(0);
2246
2247        let mut one_col_hashes = vec![0; int_array.len()];
2248        create_hashes([&int_array], &quality_state, &mut one_col_hashes).unwrap();
2249        let expected_hashes: Vec<_> = [1i32, 2, 3, 4]
2250            .iter()
2251            .map(|value| quality_state.hash_one(value))
2252            .collect();
2253        assert_eq!(one_col_hashes, expected_hashes);
2254
2255        let mut two_col_hashes = vec![0; int_array.len()];
2256        create_hashes(
2257            [&int_array, &str_array],
2258            &quality_state,
2259            &mut two_col_hashes,
2260        )
2261        .unwrap();
2262        assert_ne!(two_col_hashes, one_col_hashes);
2263    }
2264
2265    #[test]
2266    fn test_with_hashes() {
2267        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2268        let random_state = RandomState::with_seed(0);
2269
2270        // Test that with_hashes produces the same results as create_hashes
2271        let mut expected_hashes = vec![0; array.len()];
2272        create_hashes([&array], &random_state, &mut expected_hashes).unwrap();
2273
2274        let result = with_hashes([&array], &random_state, |hashes| {
2275            assert_eq!(hashes.len(), 4);
2276            // Verify hashes match expected values
2277            assert_eq!(hashes, &expected_hashes[..]);
2278            // Return a copy of the hashes
2279            Ok(hashes.to_vec())
2280        })
2281        .unwrap();
2282
2283        // Verify callback result is returned correctly
2284        assert_eq!(result, expected_hashes);
2285    }
2286
2287    #[test]
2288    fn test_with_hashes_multi_column() {
2289        let int_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
2290        let str_array: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c"]));
2291        let random_state = RandomState::with_seed(0);
2292
2293        // Test multi-column hashing
2294        let mut expected_hashes = vec![0; int_array.len()];
2295        create_hashes(
2296            [&int_array, &str_array],
2297            &random_state,
2298            &mut expected_hashes,
2299        )
2300        .unwrap();
2301
2302        with_hashes([&int_array, &str_array], &random_state, |hashes| {
2303            assert_eq!(hashes.len(), 3);
2304            assert_eq!(hashes, &expected_hashes[..]);
2305            Ok(())
2306        })
2307        .unwrap();
2308    }
2309
2310    #[test]
2311    fn test_with_hashes_empty_arrays() {
2312        let random_state = RandomState::with_seed(0);
2313
2314        // Test that passing no arrays returns an error
2315        let empty: [&ArrayRef; 0] = [];
2316        let result = with_hashes(empty, &random_state, |_hashes| Ok(()));
2317
2318        assert!(result.is_err());
2319        assert!(
2320            result
2321                .unwrap_err()
2322                .to_string()
2323                .contains("requires at least one array")
2324        );
2325    }
2326
2327    #[test]
2328    fn test_with_hashes_reentrancy() {
2329        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
2330        let array2: ArrayRef = Arc::new(Int32Array::from(vec![4, 5, 6]));
2331        let random_state = RandomState::with_seed(0);
2332
2333        // Test that reentrant calls return an error instead of panicking
2334        let result = with_hashes([&array], &random_state, |_hashes| {
2335            // Try to call with_hashes again inside the callback
2336            with_hashes([&array2], &random_state, |_inner_hashes| Ok(()))
2337        });
2338
2339        assert!(result.is_err());
2340        let err_msg = result.unwrap_err().to_string();
2341        assert!(
2342            err_msg.contains("reentrantly") || err_msg.contains("cannot be called"),
2343            "Error message should mention reentrancy: {err_msg}",
2344        );
2345    }
2346
2347    #[test]
2348    #[cfg(not(feature = "force_hash_collisions"))]
2349    fn create_hashes_for_sparse_union_arrays() {
2350        // logical array: [int(5), str("foo"), int(10), int(5)]
2351        let int_array = Int32Array::from(vec![Some(5), None, Some(10), Some(5)]);
2352        let str_array = StringArray::from(vec![None, Some("foo"), None, None]);
2353
2354        let type_ids = vec![0_i8, 1, 0, 0].into();
2355        let children = vec![
2356            Arc::new(int_array) as ArrayRef,
2357            Arc::new(str_array) as ArrayRef,
2358        ];
2359
2360        let union_fields = [
2361            (0, Arc::new(Field::new("a", DataType::Int32, true))),
2362            (1, Arc::new(Field::new("b", DataType::Utf8, true))),
2363        ]
2364        .into_iter()
2365        .collect();
2366
2367        let array = UnionArray::try_new(union_fields, type_ids, None, children).unwrap();
2368        let array_ref = Arc::new(array) as ArrayRef;
2369
2370        let random_state = RandomState::with_seed(0);
2371        let mut hashes = vec![0; array_ref.len()];
2372        create_hashes(&[array_ref], &random_state, &mut hashes).unwrap();
2373
2374        // Rows 0 and 3 both have type_id=0 (int) with value 5
2375        assert_eq!(hashes[0], hashes[3]);
2376        // Row 0 (int 5) vs Row 2 (int 10) - different values
2377        assert_ne!(hashes[0], hashes[2]);
2378        // Row 0 (int) vs Row 1 (string) - different types
2379        assert_ne!(hashes[0], hashes[1]);
2380    }
2381
2382    #[test]
2383    #[cfg(not(feature = "force_hash_collisions"))]
2384    fn create_hashes_for_sparse_union_arrays_with_nulls() {
2385        // logical array: [int(5), str("foo"), int(null), str(null)]
2386        let int_array = Int32Array::from(vec![Some(5), None, None, None]);
2387        let str_array = StringArray::from(vec![None, Some("foo"), None, None]);
2388
2389        let type_ids = vec![0, 1, 0, 1].into();
2390        let children = vec![
2391            Arc::new(int_array) as ArrayRef,
2392            Arc::new(str_array) as ArrayRef,
2393        ];
2394
2395        let union_fields = [
2396            (0, Arc::new(Field::new("a", DataType::Int32, true))),
2397            (1, Arc::new(Field::new("b", DataType::Utf8, true))),
2398        ]
2399        .into_iter()
2400        .collect();
2401
2402        let array = UnionArray::try_new(union_fields, type_ids, None, children).unwrap();
2403        let array_ref = Arc::new(array) as ArrayRef;
2404
2405        let random_state = RandomState::with_seed(0);
2406        let mut hashes = vec![0; array_ref.len()];
2407        create_hashes(&[array_ref], &random_state, &mut hashes).unwrap();
2408
2409        // row 2 (int null) and row 3 (str null) should have the same hash
2410        // because they are both null values
2411        assert_eq!(hashes[2], hashes[3]);
2412
2413        // row 0 (int 5) vs row 2 (int null) - different (value vs null)
2414        assert_ne!(hashes[0], hashes[2]);
2415
2416        // row 1 (str "foo") vs row 3 (str null) - different (value vs null)
2417        assert_ne!(hashes[1], hashes[3]);
2418    }
2419
2420    #[test]
2421    #[cfg(not(feature = "force_hash_collisions"))]
2422    fn create_hashes_for_dense_union_arrays() {
2423        // creates a dense union array with int and string types
2424        // [67, "norm", 100, "macdonald", 67]
2425        let int_array = Int32Array::from(vec![67, 100, 67]);
2426        let str_array = StringArray::from(vec!["norm", "macdonald"]);
2427
2428        let type_ids = vec![0, 1, 0, 1, 0].into();
2429        let offsets = vec![0, 0, 1, 1, 2].into();
2430        let children = vec![
2431            Arc::new(int_array) as ArrayRef,
2432            Arc::new(str_array) as ArrayRef,
2433        ];
2434
2435        let union_fields = [
2436            (0, Arc::new(Field::new("a", DataType::Int32, false))),
2437            (1, Arc::new(Field::new("b", DataType::Utf8, false))),
2438        ]
2439        .into_iter()
2440        .collect();
2441
2442        let array =
2443            UnionArray::try_new(union_fields, type_ids, Some(offsets), children).unwrap();
2444        let array_ref = Arc::new(array) as ArrayRef;
2445
2446        let random_state = RandomState::with_seed(0);
2447        let mut hashes = vec![0; array_ref.len()];
2448        create_hashes(&[array_ref], &random_state, &mut hashes).unwrap();
2449
2450        // 67 vs "norm"
2451        assert_ne!(hashes[0], hashes[1]);
2452        // 67 vs 100
2453        assert_ne!(hashes[0], hashes[2]);
2454        // "norm" vs "macdonald"
2455        assert_ne!(hashes[1], hashes[3]);
2456        // 100 vs "macdonald"
2457        assert_ne!(hashes[2], hashes[3]);
2458        // 67 vs 67
2459        assert_eq!(hashes[0], hashes[4]);
2460    }
2461
2462    #[test]
2463    #[cfg(not(feature = "force_hash_collisions"))]
2464    fn create_hashes_for_union_arrays_match_selected_values() {
2465        // In sparse unions both string children are masked, the others use `take`
2466        let children = |lens: [usize; 5]| -> Vec<ArrayRef> {
2467            let ints = |len| {
2468                Int32Array::from_iter((0..len as i32).map(|v| (v % 3 != 1).then_some(v)))
2469            };
2470            let views = (0..lens[0]).map(|v| format!("longer than inline {}", v % 2));
2471            let strings = (0..lens[1]).map(|v| (v % 3 != 1).then(|| format!("s{v}")));
2472            let large = (0..lens[4]).map(|v| (v % 2 == 0).then(|| format!("l{v}")));
2473            vec![
2474                Arc::new(StringViewArray::from_iter_values(views)),
2475                Arc::new(StringArray::from_iter(strings)),
2476                Arc::new(StructArray::from(vec![(
2477                    Arc::new(Field::new("i", DataType::Int32, true)),
2478                    Arc::new(ints(lens[2])) as ArrayRef,
2479                )])),
2480                Arc::new(NullArray::new(lens[3])),
2481                Arc::new(LargeStringArray::from_iter(large)),
2482            ]
2483        };
2484        let fields: UnionFields = [0, 3, 5, 7, 9]
2485            .into_iter()
2486            .zip(children([0; 5]))
2487            .map(|(id, c)| (id, Arc::new(Field::new("", c.data_type().clone(), true))))
2488            .collect();
2489        let type_ids = ScalarBuffer::from(vec![0, 3, 9, 0, 0, 0, 5, 7, 3, 9]);
2490        let offsets = ScalarBuffer::from(vec![0, 0, 0, 1, 2, 3, 0, 0, 1, 1]);
2491        let sparse = UnionArray::try_new(
2492            fields.clone(),
2493            type_ids.clone(),
2494            None,
2495            children([10; 5]),
2496        )
2497        .unwrap();
2498        // Utf8 selecting too few rows to mask is hashed through `take` instead
2499        let few_strings = (0..40).map(|i| if i == 20 { 3 } else { [0, 5, 7][i % 3] });
2500        let sparse_few_strings = UnionArray::try_new(
2501            fields.clone(),
2502            few_strings.collect(),
2503            None,
2504            children([40; 5]),
2505        )
2506        .unwrap();
2507        let dense = UnionArray::try_new(
2508            fields,
2509            type_ids,
2510            Some(offsets),
2511            children([4, 2, 1, 1, 2]),
2512        )
2513        .unwrap();
2514
2515        for union in [
2516            sparse.clone(),
2517            sparse.slice(1, 6),
2518            sparse.slice(3, 3), // every row selects the same child
2519            sparse_few_strings,
2520            dense.clone(),
2521            dense.slice(2, 4),
2522        ] {
2523            assert_union_hashes_match_selected_values(&union, |arrays, hashes| {
2524                let random_state = RandomState::with_seed(0);
2525                create_hashes(arrays.iter().copied(), &random_state, hashes).unwrap();
2526            });
2527            assert_union_hashes_match_selected_values(&union, |arrays, hashes| {
2528                let hasher = BuildHasherDefault::<TestHasher>::default();
2529                create_hashes_with_hasher(arrays.iter().copied(), &hasher, hashes)
2530                    .unwrap();
2531            });
2532        }
2533    }
2534
2535    /// Asserts each union row contributes the hash of its selected value on its own
2536    #[cfg(not(feature = "force_hash_collisions"))]
2537    fn assert_union_hashes_match_selected_values(
2538        union: &UnionArray,
2539        create_hashes: impl Fn(&[&dyn Array], &mut [u64]),
2540    ) {
2541        let prev = Int64Array::from_iter_values(0..union.len() as i64);
2542        let mut prev_hashes = vec![0; union.len()];
2543        create_hashes(&[&prev], &mut prev_hashes);
2544
2545        let mut hashes = vec![0; union.len()];
2546        create_hashes(&[&prev, union], &mut hashes);
2547        for (i, hash) in hashes.into_iter().enumerate() {
2548            let value = union
2549                .child(union.type_id(i))
2550                .slice(union.value_offset(i), 1);
2551            let mut value_hash = [0];
2552            create_hashes(&[&value], &mut value_hash);
2553            let expected = combine_hashes(prev_hashes[i], value_hash[0]);
2554            assert_eq!(hash, expected, "row {i} of {union:?}");
2555        }
2556    }
2557
2558    #[test]
2559    #[cfg(not(feature = "force_hash_collisions"))]
2560    fn create_hashes_for_sliced_run_array() -> Result<()> {
2561        let values = Arc::new(Int32Array::from(vec![10, 20, 30]));
2562        let run_ends = Arc::new(Int32Array::from(vec![2, 5, 7]));
2563        let array = Arc::new(RunArray::try_new(&run_ends, values.as_ref()).unwrap());
2564
2565        let random_state = RandomState::with_seed(0);
2566        let mut full_hashes = vec![0; array.len()];
2567        create_hashes(
2568            &[Arc::clone(&array) as ArrayRef],
2569            &random_state,
2570            &mut full_hashes,
2571        )?;
2572
2573        let array_ref: ArrayRef = Arc::clone(&array) as ArrayRef;
2574        let sliced_array = array_ref.slice(2, 3);
2575
2576        let mut sliced_hashes = vec![0; sliced_array.len()];
2577        create_hashes(
2578            std::slice::from_ref(&sliced_array),
2579            &random_state,
2580            &mut sliced_hashes,
2581        )?;
2582
2583        assert_eq!(sliced_hashes.len(), 3);
2584        assert_eq!(sliced_hashes[0], sliced_hashes[1]);
2585        assert_eq!(sliced_hashes[1], sliced_hashes[2]);
2586        assert_eq!(&sliced_hashes, &full_hashes[2..5]);
2587
2588        Ok(())
2589    }
2590
2591    #[test]
2592    #[cfg(not(feature = "force_hash_collisions"))]
2593    fn test_run_array_with_nulls() -> Result<()> {
2594        let values = Arc::new(Int32Array::from(vec![Some(10), None, Some(20)]));
2595        let run_ends = Arc::new(Int32Array::from(vec![2, 4, 6]));
2596        let array = Arc::new(RunArray::try_new(&run_ends, values.as_ref()).unwrap());
2597
2598        let random_state = RandomState::with_seed(0);
2599        let mut hashes = vec![0; array.len()];
2600        create_hashes(
2601            &[Arc::clone(&array) as ArrayRef],
2602            &random_state,
2603            &mut hashes,
2604        )?;
2605
2606        assert_eq!(hashes[0], hashes[1]);
2607        assert_ne!(hashes[0], 0);
2608        assert_eq!(hashes[2], hashes[3]);
2609        assert_eq!(hashes[2], 0);
2610        assert_eq!(hashes[4], hashes[5]);
2611        assert_ne!(hashes[4], 0);
2612        assert_ne!(hashes[0], hashes[4]);
2613
2614        Ok(())
2615    }
2616
2617    #[test]
2618    #[cfg(not(feature = "force_hash_collisions"))]
2619    fn test_run_array_with_nulls_multicolumn() -> Result<()> {
2620        let primitive_array = Arc::new(Int32Array::from(vec![Some(10), None, Some(20)]));
2621        let run_values = Arc::new(Int32Array::from(vec![Some(10), None, Some(20)]));
2622        let run_ends = Arc::new(Int32Array::from(vec![1, 2, 3]));
2623        let run_array =
2624            Arc::new(RunArray::try_new(&run_ends, run_values.as_ref()).unwrap());
2625        let second_col = Arc::new(Int32Array::from(vec![100, 200, 300]));
2626
2627        let random_state = RandomState::with_seed(0);
2628
2629        let mut primitive_hashes = vec![0; 3];
2630        create_hashes(
2631            &[
2632                Arc::clone(&primitive_array) as ArrayRef,
2633                Arc::clone(&second_col) as ArrayRef,
2634            ],
2635            &random_state,
2636            &mut primitive_hashes,
2637        )?;
2638
2639        let mut run_hashes = vec![0; 3];
2640        create_hashes(
2641            &[
2642                Arc::clone(&run_array) as ArrayRef,
2643                Arc::clone(&second_col) as ArrayRef,
2644            ],
2645            &random_state,
2646            &mut run_hashes,
2647        )?;
2648
2649        assert_eq!(primitive_hashes, run_hashes);
2650
2651        Ok(())
2652    }
2653}