1use 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
21pub type RandomState = FixedState;
29pub type QualityRandomState = foldhash::quality::FixedState;
30
31pub const HLL_RANDOM_STATE: QualityRandomState = QualityRandomState::with_seed(0);
36
37pub 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#[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
93const MAX_BUFFER_SIZE: usize = 524_288;
98
99thread_local! {
100 static HASH_BUFFER: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
105}
106
107pub 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 let mut iter = arrays.into_iter().peekable();
150
151 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 buffer.clear();
163 buffer.resize(required_size, 0);
164
165 create_hashes(iter, random_state, &mut buffer[..required_size])?;
167
168 let result = callback(&buffer[..required_size])?;
170
171 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
181pub 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 *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 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 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#[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#[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#[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#[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#[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 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 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 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#[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 match (
496 array.null_count() != 0,
497 !array.data_buffers().is_empty(),
498 rehash,
499 ) {
500 (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#[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 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 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#[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 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 let mut values_hashes = vec![0u64; row_len];
694 child_hashing.create_hashes(array.columns(), &mut values_hashes)?;
695
696 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#[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 let (first_offset, entries_len) = offset_span(offsets);
724
725 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 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 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#[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 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#[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 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 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#[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#[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 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 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#[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 return _internal_err!(
1226 "Unsupported data type in hasher: {}",
1227 array.data_type()
1228 );
1229 }
1230 }
1231 Ok(())
1232}
1233
1234#[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
1248pub 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
1285pub 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 let rehash = i >= 1;
1301 hash_single_array(array.as_dyn_array(), random_state, hashes_buffer, rehash)?;
1302 }
1303 Ok(hashes_buffer)
1304}
1305
1306pub 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 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 assert_eq!(binary[0], binary[5]);
1442 assert_eq!(binary[4], binary[6]);
1443
1444 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 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 assert_eq!(string_hashes, dict_hashes);
1512
1513 assert_eq!(strings[0], strings[5]);
1515 assert_eq!(strings[4], strings[6]);
1516
1517 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 #[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 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 assert_eq!(string_hashes, dict_hashes);
1829
1830 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 assert_ne!(strings[0], strings[2]);
1838 assert_ne!(dict_hashes[0], dict_hashes[2]);
1839 }
1840
1841 #[test]
1842 #[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]); }
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 Some(vec![Some(3), None, Some(5)]),
1873 Some(vec![Some(3), None, Some(5)]),
1874 None,
1875 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 #[cfg(not(feature = "force_hash_collisions"))]
1892 fn create_hashes_for_list_view_arrays() {
1893 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 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]); assert_eq!(hashes[1], hashes[4]); assert_eq!(hashes[2], hashes[3]); assert_eq!(hashes[1], hashes[6]); assert_ne!(hashes[0], hashes[2]); assert_ne!(hashes[0], hashes[6]); assert_ne!(hashes[2], hashes[6]); }
1936
1937 #[test]
1938 #[cfg(not(feature = "force_hash_collisions"))]
1940 fn create_hashes_for_large_list_view_arrays() {
1941 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 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]); assert_eq!(hashes[1], hashes[4]); assert_eq!(hashes[2], hashes[3]); assert_eq!(hashes[1], hashes[6]); assert_ne!(hashes[0], hashes[2]); assert_ne!(hashes[0], hashes[6]); assert_ne!(hashes[2], hashes[6]); }
1984
1985 #[test]
1986 #[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 #[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 assert_ne!(hashes[2], hashes[3]);
2057 assert_eq!(hashes[4], hashes[5]);
2059 }
2060
2061 #[test]
2062 #[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 #[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 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 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 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 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 builder.keys().append_value("key1");
2126 builder.values().append_value(1);
2127 builder.append(true).unwrap();
2128 builder.keys().append_value("key1");
2130 builder.values().append_null();
2131 builder.append(true).unwrap();
2132 builder.append(true).unwrap();
2134 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]); assert_ne!(hashes[0], hashes[2]); assert_ne!(hashes[0], hashes[3]); assert_ne!(hashes[0], hashes[4]); assert_ne!(hashes[4], hashes[5]); assert_eq!(hashes[6], hashes[7]); }
2151
2152 #[test]
2153 #[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 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 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 assert_eq!(hashes, &expected_hashes[..]);
2278 Ok(hashes.to_vec())
2280 })
2281 .unwrap();
2282
2283 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 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 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 let result = with_hashes([&array], &random_state, |_hashes| {
2335 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 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 assert_eq!(hashes[0], hashes[3]);
2376 assert_ne!(hashes[0], hashes[2]);
2378 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 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 assert_eq!(hashes[2], hashes[3]);
2412
2413 assert_ne!(hashes[0], hashes[2]);
2415
2416 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 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 assert_ne!(hashes[0], hashes[1]);
2452 assert_ne!(hashes[0], hashes[2]);
2454 assert_ne!(hashes[1], hashes[3]);
2456 assert_ne!(hashes[2], hashes[3]);
2458 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 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 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), 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 #[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}