Skip to main content

arrow_array/builder/
generic_bytes_dictionary_builder.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
5use crate::builder::{ArrayBuilder, GenericByteBuilder, PrimitiveBuilder};
6use crate::types::{ArrowDictionaryKeyType, ByteArrayType, GenericBinaryType, GenericStringType};
7use crate::{
8    Array, ArrayRef, DictionaryArray, GenericByteArray, PrimitiveArray, TypedDictionaryArray,
9};
10use arrow_buffer::ArrowNativeType;
11use arrow_schema::ArrowError;
12use hashbrown::HashTable;
13use num_traits::NumCast;
14use std::any::Any;
15use std::sync::Arc;
16
17/// Builder for [`DictionaryArray`] of [`GenericByteArray`]
18///
19/// For example to map a set of byte indices to String values. Note that
20/// the use of a `HashMap` here will not scale to very large arrays or
21/// result in an ordered dictionary.
22#[derive(Debug)]
23pub struct GenericByteDictionaryBuilder<K, T>
24where
25    K: ArrowDictionaryKeyType,
26    T: ByteArrayType,
27{
28    state: ahash::RandomState,
29    dedup: HashTable<usize>,
30
31    keys_builder: PrimitiveBuilder<K>,
32    values_builder: GenericByteBuilder<T>,
33}
34
35impl<K, T> Default for GenericByteDictionaryBuilder<K, T>
36where
37    K: ArrowDictionaryKeyType,
38    T: ByteArrayType,
39{
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl<K, T> GenericByteDictionaryBuilder<K, T>
46where
47    K: ArrowDictionaryKeyType,
48    T: ByteArrayType,
49{
50    /// Creates a new `GenericByteDictionaryBuilder`
51    pub fn new() -> Self {
52        let keys_builder = PrimitiveBuilder::new();
53        let values_builder = GenericByteBuilder::<T>::new();
54        Self {
55            state: Default::default(),
56            dedup: HashTable::with_capacity(keys_builder.capacity()),
57            keys_builder,
58            values_builder,
59        }
60    }
61
62    /// Creates a new `GenericByteDictionaryBuilder` with the provided capacities
63    ///
64    /// `keys_capacity`: the number of keys, i.e. length of array to build
65    /// `value_capacity`: the number of distinct dictionary values, i.e. size of dictionary
66    /// `data_capacity`: the total number of bytes of all distinct bytes in the dictionary
67    pub fn with_capacity(
68        keys_capacity: usize,
69        value_capacity: usize,
70        data_capacity: usize,
71    ) -> Self {
72        Self {
73            state: Default::default(),
74            dedup: HashTable::with_capacity(value_capacity),
75            keys_builder: PrimitiveBuilder::with_capacity(keys_capacity),
76            values_builder: GenericByteBuilder::<T>::with_capacity(value_capacity, data_capacity),
77        }
78    }
79
80    /// Creates a new `GenericByteDictionaryBuilder` from a keys capacity and a dictionary
81    /// which is initialized with the given values.
82    /// The indices of those dictionary values are used as keys.
83    ///
84    /// # Example
85    ///
86    /// ```
87    /// # use arrow_array::builder::StringDictionaryBuilder;
88    /// # use arrow_array::{Int16Array, StringArray};
89    ///
90    /// let dictionary_values = StringArray::from(vec![None, Some("abc"), Some("def")]);
91    ///
92    /// let mut builder = StringDictionaryBuilder::new_with_dictionary(3, &dictionary_values).unwrap();
93    /// builder.append("def").unwrap();
94    /// builder.append_null();
95    /// builder.append("abc").unwrap();
96    ///
97    /// let dictionary_array = builder.finish();
98    ///
99    /// let keys = dictionary_array.keys();
100    ///
101    /// assert_eq!(keys, &Int16Array::from(vec![Some(2), None, Some(1)]));
102    /// ```
103    pub fn new_with_dictionary(
104        keys_capacity: usize,
105        dictionary_values: &GenericByteArray<T>,
106    ) -> Result<Self, ArrowError> {
107        let state = ahash::RandomState::default();
108        let dict_len = dictionary_values.len();
109
110        let mut dedup = HashTable::with_capacity(dict_len);
111
112        let values_len = dictionary_values.value_data().len();
113        let mut values_builder = GenericByteBuilder::<T>::with_capacity(dict_len, values_len);
114
115        K::Native::from_usize(dictionary_values.len())
116            .ok_or(ArrowError::DictionaryKeyOverflowError)?;
117
118        for (idx, maybe_value) in dictionary_values.iter().enumerate() {
119            match maybe_value {
120                Some(value) => {
121                    let value_bytes: &[u8] = value.as_ref();
122                    let hash = state.hash_one(value_bytes);
123
124                    dedup
125                        .entry(
126                            hash,
127                            |idx: &usize| value_bytes == get_bytes(&values_builder, *idx),
128                            |idx: &usize| state.hash_one(get_bytes(&values_builder, *idx)),
129                        )
130                        .or_insert(idx);
131
132                    values_builder.append_value(value);
133                }
134                None => values_builder.append_null(),
135            }
136        }
137
138        Ok(Self {
139            state,
140            dedup,
141            keys_builder: PrimitiveBuilder::with_capacity(keys_capacity),
142            values_builder,
143        })
144    }
145
146    /// Creates a new `GenericByteDictionaryBuilder` from the existing builder with the same
147    /// keys and values, but with a new data type for the keys.
148    ///
149    /// # Example
150    /// ```
151    /// #
152    /// # use arrow_array::builder::StringDictionaryBuilder;
153    /// # use arrow_array::types::{UInt8Type, UInt16Type};
154    /// # use arrow_array::UInt16Array;
155    /// # use arrow_schema::ArrowError;
156    ///
157    /// let mut u8_keyed_builder = StringDictionaryBuilder::<UInt8Type>::new();
158    ///
159    /// // appending too many values causes the dictionary to overflow
160    /// for i in 0..256 {
161    ///     u8_keyed_builder.append_value(format!("{}", i));
162    /// }
163    /// let result = u8_keyed_builder.append("256");
164    /// assert!(matches!(result, Err(ArrowError::DictionaryKeyOverflowError{})));
165    ///
166    /// // we need to upgrade to a larger key type
167    /// let mut u16_keyed_builder = StringDictionaryBuilder::<UInt16Type>::try_new_from_builder(u8_keyed_builder).unwrap();
168    /// let dictionary_array = u16_keyed_builder.finish();
169    /// let keys = dictionary_array.keys();
170    ///
171    /// assert_eq!(keys, &UInt16Array::from_iter(0..256));
172    /// ```
173    pub fn try_new_from_builder<K2>(
174        mut source: GenericByteDictionaryBuilder<K2, T>,
175    ) -> Result<Self, ArrowError>
176    where
177        K::Native: NumCast,
178        K2: ArrowDictionaryKeyType,
179        K2::Native: NumCast,
180    {
181        let state = source.state;
182        let dedup = source.dedup;
183        let values_builder = source.values_builder;
184
185        let source_keys = source.keys_builder.finish();
186        let new_keys: PrimitiveArray<K> = source_keys.try_unary(|value| {
187            num_traits::cast::cast::<K2::Native, K::Native>(value).ok_or_else(|| {
188                ArrowError::CastError(format!(
189                    "Can't cast dictionary keys from source type {:?} to type {:?}",
190                    K2::DATA_TYPE,
191                    K::DATA_TYPE
192                ))
193            })
194        })?;
195
196        // drop source key here because currently source_keys and new_keys are holding reference to
197        // the same underlying null_buffer. Below we want to call new_keys.into_builder() it must
198        // be the only reference holder.
199        drop(source_keys);
200
201        Ok(Self {
202            state,
203            dedup,
204            keys_builder: new_keys.into_builder().map_err(|_| {
205                ArrowError::ComputeError(
206                    "Internal Error: the keys just derived from the source builder are \
207                     unexpectedly shared, so they cannot be reused as a builder"
208                        .to_string(),
209                )
210            })?,
211            values_builder,
212        })
213    }
214}
215
216impl<K, T> ArrayBuilder for GenericByteDictionaryBuilder<K, T>
217where
218    K: ArrowDictionaryKeyType,
219    T: ByteArrayType,
220{
221    /// Returns the builder as an non-mutable `Any` reference.
222    fn as_any(&self) -> &dyn Any {
223        self
224    }
225
226    /// Returns the builder as an mutable `Any` reference.
227    fn as_any_mut(&mut self) -> &mut dyn Any {
228        self
229    }
230
231    /// Returns the boxed builder as a box of `Any`.
232    fn into_box_any(self: Box<Self>) -> Box<dyn Any> {
233        self
234    }
235
236    /// Returns the number of array slots in the builder
237    fn len(&self) -> usize {
238        self.keys_builder.len()
239    }
240
241    /// Builds the array and reset this builder.
242    fn finish(&mut self) -> ArrayRef {
243        Arc::new(self.finish())
244    }
245
246    /// Builds the array without resetting the builder.
247    fn finish_cloned(&self) -> ArrayRef {
248        Arc::new(self.finish_cloned())
249    }
250
251    fn finish_preserve_values(&mut self) -> ArrayRef {
252        Arc::new(self.finish_preserve_values())
253    }
254}
255
256impl<K, T> GenericByteDictionaryBuilder<K, T>
257where
258    K: ArrowDictionaryKeyType,
259    T: ByteArrayType,
260{
261    fn get_or_insert_key(&mut self, value: impl AsRef<T::Native>) -> Result<K::Native, ArrowError> {
262        let value: &T::Native = value.as_ref();
263        let value_bytes: &[u8] = value.as_ref();
264
265        let state = &self.state;
266        let storage = &mut self.values_builder;
267        let hash = state.hash_one(value_bytes);
268
269        let idx = *self
270            .dedup
271            .entry(
272                hash,
273                |idx| value_bytes == get_bytes(storage, *idx),
274                |idx| state.hash_one(get_bytes(storage, *idx)),
275            )
276            .or_insert_with(|| {
277                let idx = storage.len();
278                storage.append_value(value);
279                idx
280            })
281            .get();
282
283        let key = K::Native::from_usize(idx).ok_or(ArrowError::DictionaryKeyOverflowError)?;
284
285        Ok(key)
286    }
287
288    /// Append a value to the array. Return an existing index
289    /// if already present in the values array or a new index if the
290    /// value is appended to the values array.
291    ///
292    /// Returns an error if the new index would overflow the key type.
293    pub fn append(&mut self, value: impl AsRef<T::Native>) -> Result<K::Native, ArrowError> {
294        let key = self.get_or_insert_key(value)?;
295        self.keys_builder.append_value(key);
296        Ok(key)
297    }
298
299    /// Append a value multiple times to the array.
300    /// This is the same as `append` but allows to append the same value multiple times without doing multiple lookups.
301    ///
302    /// Returns an error if the new index would overflow the key type.
303    pub fn append_n(
304        &mut self,
305        value: impl AsRef<T::Native>,
306        count: usize,
307    ) -> Result<K::Native, ArrowError> {
308        let key = self.get_or_insert_key(value)?;
309        self.keys_builder.append_value_n(key, count);
310        Ok(key)
311    }
312
313    /// Infallibly append a value to this builder
314    ///
315    /// # Panics
316    ///
317    /// Panics if the resulting length of the dictionary values array would exceed `T::Native::MAX`
318    pub fn append_value(&mut self, value: impl AsRef<T::Native>) {
319        self.append(value).expect("dictionary key overflow");
320    }
321
322    /// Infallibly append a value to this builder repeatedly `count` times.
323    /// This is the same as `append_value` but allows to append the same value multiple times without doing multiple lookups.
324    ///
325    /// # Panics
326    ///
327    /// Panics if the resulting length of the dictionary values array would exceed `T::Native::MAX`
328    pub fn append_values(&mut self, value: impl AsRef<T::Native>, count: usize) {
329        self.append_n(value, count)
330            .expect("dictionary key overflow");
331    }
332
333    /// Appends a null slot into the builder
334    #[inline]
335    pub fn append_null(&mut self) {
336        self.keys_builder.append_null()
337    }
338
339    /// Infallibly append `n` null slots into the builder
340    #[inline]
341    pub fn append_nulls(&mut self, n: usize) {
342        self.keys_builder.append_nulls(n)
343    }
344
345    /// Append an `Option` value into the builder
346    ///
347    /// # Panics
348    ///
349    /// Panics if the resulting length of the dictionary values array would exceed `T::Native::MAX`
350    #[inline]
351    pub fn append_option(&mut self, value: Option<impl AsRef<T::Native>>) {
352        match value {
353            None => self.append_null(),
354            Some(v) => self.append_value(v),
355        }
356    }
357
358    /// Append an `Option` value into the builder repeatedly `count` times.
359    /// This is the same as `append_option` but allows to append the same value multiple times without doing multiple lookups.
360    ///
361    /// # Panics
362    ///
363    /// Panics if the resulting length of the dictionary values array would exceed `T::Native::MAX`
364    pub fn append_options(&mut self, value: Option<impl AsRef<T::Native>>, count: usize) {
365        match value {
366            None => self.keys_builder.append_nulls(count),
367            Some(v) => self.append_values(v, count),
368        }
369    }
370
371    /// Append all values from a [`GenericByteArray`] into this builder.
372    ///
373    /// This is more efficient than calling [`Self::append`] in a loop because
374    /// it accesses the raw offset/value buffers directly and bulk-writes the
375    /// resolved keys with a single `append_slice` / `append_values` call.
376    ///
377    /// Returns an error if any new dictionary index would overflow the key type.
378    pub fn append_array(&mut self, array: &GenericByteArray<T>) -> Result<(), ArrowError> {
379        let row_count = array.len();
380        if row_count == 0 {
381            return Ok(());
382        }
383        let offsets = array.value_offsets();
384        let raw_data = array.value_data();
385
386        match array.nulls() {
387            None => {
388                let mut key_buf: Vec<K::Native> = Vec::with_capacity(row_count);
389                for row_idx in 0..row_count {
390                    key_buf.push(resolve_key::<K, T>(
391                        row_idx,
392                        offsets,
393                        raw_data,
394                        array,
395                        &mut self.dedup,
396                        &self.state,
397                        &mut self.values_builder,
398                    )?);
399                }
400                self.keys_builder.append_slice(&key_buf);
401            }
402            Some(nulls) => {
403                let mut key_buf: Vec<K::Native> = Vec::with_capacity(row_count);
404                let mut valid_buf: Vec<bool> = Vec::with_capacity(row_count);
405                for row_idx in 0..row_count {
406                    if nulls.is_null(row_idx) {
407                        key_buf.push(K::Native::usize_as(0));
408                        valid_buf.push(false);
409                    } else {
410                        key_buf.push(resolve_key::<K, T>(
411                            row_idx,
412                            offsets,
413                            raw_data,
414                            array,
415                            &mut self.dedup,
416                            &self.state,
417                            &mut self.values_builder,
418                        )?);
419                        valid_buf.push(true);
420                    }
421                }
422                self.keys_builder.append_values(&key_buf, &valid_buf);
423            }
424        }
425        Ok(())
426    }
427
428    /// Extends builder with an existing dictionary array.
429    ///
430    /// This is the same as [`Self::extend`] but is faster as it translates
431    /// the dictionary values once rather than doing a lookup for each item in the iterator
432    ///
433    /// when dictionary values are null (the actual mapped values) the keys are null
434    ///
435    pub fn extend_dictionary(
436        &mut self,
437        dictionary: &TypedDictionaryArray<K, GenericByteArray<T>>,
438    ) -> Result<(), ArrowError> {
439        let values = dictionary.values();
440
441        let v_len = values.len();
442        let k_len = dictionary.keys().len();
443        if v_len == 0 && k_len == 0 {
444            return Ok(());
445        }
446
447        // All nulls
448        if v_len == 0 {
449            self.append_nulls(k_len);
450            return Ok(());
451        }
452
453        if k_len == 0 {
454            return Err(ArrowError::InvalidArgumentError(
455                "Dictionary keys should not be empty when values are not empty".to_string(),
456            ));
457        }
458
459        // Orphan values will be carried over to the new dictionary
460        let mapped_values = values
461            .iter()
462            // Dictionary values can technically be null, so we need to handle that
463            .map(|dict_value| {
464                dict_value
465                    .map(|dict_value| self.get_or_insert_key(dict_value))
466                    .transpose()
467            })
468            .collect::<Result<Vec<_>, _>>()?;
469
470        // Just insert the keys without additional lookups
471        dictionary.keys().iter().for_each(|key| match key {
472            None => self.append_null(),
473            Some(original_dict_index) => {
474                let index = original_dict_index.as_usize().min(v_len - 1);
475                match mapped_values[index] {
476                    None => self.append_null(),
477                    Some(mapped_value) => self.keys_builder.append_value(mapped_value),
478                }
479            }
480        });
481
482        Ok(())
483    }
484
485    /// Builds the `DictionaryArray` and reset this builder.
486    pub fn finish(&mut self) -> DictionaryArray<K> {
487        self.dedup.clear();
488        let values = self.values_builder.finish();
489        let keys = self.keys_builder.finish();
490
491        // SAFETY: keys and values were produced by this builder; the builder
492        // only appends keys that index into the values it has built so far.
493        unsafe { DictionaryArray::new_unchecked(keys, Arc::new(values)) }
494    }
495
496    /// Builds the `DictionaryArray` without resetting the builder.
497    pub fn finish_cloned(&self) -> DictionaryArray<K> {
498        let values = self.values_builder.finish_cloned();
499        let keys = self.keys_builder.finish_cloned();
500
501        // SAFETY: keys and values were produced by this builder; the builder
502        // only appends keys that index into the values it has built so far.
503        unsafe { DictionaryArray::new_unchecked(keys, Arc::new(values)) }
504    }
505
506    /// Builds the `DictionaryArray` without resetting the values builder or
507    /// the internal de-duplication map.
508    ///
509    /// The advantage of doing this is that the values will represent the entire
510    /// set of what has been built so-far by this builder and ensures
511    /// consistency in the assignment of keys to values across multiple calls
512    /// to `finish_preserve_values`. This enables ipc writers to efficiently
513    /// emit delta dictionaries.
514    ///
515    /// The downside to this is that building the record requires creating a
516    /// copy of the values, which can become slowly more expensive if the
517    /// dictionary grows.
518    ///
519    /// Additionally, if record batches from multiple different dictionary
520    /// builders for the same column are fed into a single ipc writer, beware
521    /// that entire dictionaries are likely to be re-sent frequently even when
522    /// the majority of the values are not used by the current record batch.
523    pub fn finish_preserve_values(&mut self) -> DictionaryArray<K> {
524        let values = self.values_builder.finish_cloned();
525        let keys = self.keys_builder.finish();
526
527        // SAFETY: keys and values were produced by this builder; the builder
528        // only appends keys that index into the values it has built so far.
529        unsafe { DictionaryArray::new_unchecked(keys, Arc::new(values)) }
530    }
531
532    /// Returns the current null buffer as a slice
533    pub fn validity_slice(&self) -> Option<&[u8]> {
534        self.keys_builder.validity_slice()
535    }
536}
537
538impl<K: ArrowDictionaryKeyType, T: ByteArrayType, V: AsRef<T::Native>> Extend<Option<V>>
539    for GenericByteDictionaryBuilder<K, T>
540{
541    #[inline]
542    fn extend<I: IntoIterator<Item = Option<V>>>(&mut self, iter: I) {
543        for v in iter {
544            self.append_option(v)
545        }
546    }
547}
548
549#[inline]
550fn resolve_key<K, T>(
551    row_idx: usize,
552    offsets: &[T::Offset],
553    raw_data: &[u8],
554    array: &GenericByteArray<T>,
555    dedup: &mut HashTable<usize>,
556    state: &ahash::RandomState,
557    storage: &mut GenericByteBuilder<T>,
558) -> Result<K::Native, ArrowError>
559where
560    K: ArrowDictionaryKeyType,
561    T: ByteArrayType,
562{
563    let start = offsets[row_idx].as_usize();
564    let end = offsets[row_idx + 1].as_usize();
565    // SAFETY: offsets are valid by GenericByteArray invariants
566    let bytes = unsafe { raw_data.get_unchecked(start..end) };
567    let hash = state.hash_one(bytes);
568    let dict_idx = *dedup
569        .entry(
570            hash,
571            |idx| bytes == get_bytes(storage, *idx),
572            |idx| state.hash_one(get_bytes(storage, *idx)),
573        )
574        .or_insert_with(|| {
575            let idx = storage.len();
576            // SAFETY: row_idx < row_count = array.len(), slot is non-null
577            storage.append_value(unsafe { array.value_unchecked(row_idx) });
578            idx
579        })
580        .get();
581    K::Native::from_usize(dict_idx).ok_or(ArrowError::DictionaryKeyOverflowError)
582}
583
584fn get_bytes<T: ByteArrayType>(values: &GenericByteBuilder<T>, idx: usize) -> &[u8] {
585    let offsets = values.offsets_slice();
586    let values = values.values_slice();
587
588    let end_offset = offsets[idx + 1].as_usize();
589    let start_offset = offsets[idx].as_usize();
590
591    &values[start_offset..end_offset]
592}
593
594/// Builder for [`DictionaryArray`] of [`StringArray`](crate::array::StringArray)
595///
596/// ```
597/// // Create a dictionary array indexed by bytes whose values are Strings.
598/// // It can thus hold up to 256 distinct string values.
599///
600/// # use arrow_array::builder::StringDictionaryBuilder;
601/// # use arrow_array::{Int8Array, StringArray};
602/// # use arrow_array::types::Int8Type;
603///
604/// let mut builder = StringDictionaryBuilder::<Int8Type>::new();
605///
606/// // The builder builds the dictionary value by value
607/// builder.append("abc").unwrap();
608/// builder.append_null();
609/// builder.append_n("def", 2).unwrap();  // appends "def" twice with a single lookup
610/// builder.append("abc").unwrap();
611/// let array = builder.finish();
612///
613/// assert_eq!(
614///   array.keys(),
615///   &Int8Array::from(vec![Some(0), None, Some(1), Some(1), Some(0)])
616/// );
617///
618/// // Values are polymorphic and so require a downcast.
619/// let av = array.values();
620/// let ava: &StringArray = av.as_any().downcast_ref::<StringArray>().unwrap();
621///
622/// assert_eq!(ava.value(0), "abc");
623/// assert_eq!(ava.value(1), "def");
624///
625/// ```
626pub type StringDictionaryBuilder<K> = GenericByteDictionaryBuilder<K, GenericStringType<i32>>;
627
628/// Builder for [`DictionaryArray`] of [`LargeStringArray`](crate::array::LargeStringArray)
629pub type LargeStringDictionaryBuilder<K> = GenericByteDictionaryBuilder<K, GenericStringType<i64>>;
630
631/// Builder for [`DictionaryArray`] of [`BinaryArray`](crate::array::BinaryArray)
632///
633/// ```
634/// // Create a dictionary array indexed by bytes whose values are binary.
635/// // It can thus hold up to 256 distinct binary values.
636///
637/// # use arrow_array::builder::BinaryDictionaryBuilder;
638/// # use arrow_array::{BinaryArray, Int8Array};
639/// # use arrow_array::types::Int8Type;
640///
641/// let mut builder = BinaryDictionaryBuilder::<Int8Type>::new();
642///
643/// // The builder builds the dictionary value by value
644/// builder.append(b"abc").unwrap();
645/// builder.append_null();
646/// builder.append(b"def").unwrap();
647/// builder.append(b"def").unwrap();
648/// builder.append(b"abc").unwrap();
649/// let array = builder.finish();
650///
651/// assert_eq!(
652///   array.keys(),
653///   &Int8Array::from(vec![Some(0), None, Some(1), Some(1), Some(0)])
654/// );
655///
656/// // Values are polymorphic and so require a downcast.
657/// let av = array.values();
658/// let ava: &BinaryArray = av.as_any().downcast_ref::<BinaryArray>().unwrap();
659///
660/// assert_eq!(ava.value(0), b"abc");
661/// assert_eq!(ava.value(1), b"def");
662///
663/// ```
664pub type BinaryDictionaryBuilder<K> = GenericByteDictionaryBuilder<K, GenericBinaryType<i32>>;
665
666/// Builder for [`DictionaryArray`] of [`LargeBinaryArray`](crate::array::LargeBinaryArray)
667pub type LargeBinaryDictionaryBuilder<K> = GenericByteDictionaryBuilder<K, GenericBinaryType<i64>>;
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    use crate::array::Int8Array;
674    use crate::cast::AsArray;
675    use crate::types::{
676        BinaryType, Int8Type, Int16Type, Int32Type, UInt8Type, UInt16Type, Utf8Type,
677    };
678    use crate::{ArrowPrimitiveType, BinaryArray, StringArray};
679    use arrow_schema::DataType;
680
681    fn test_bytes_dictionary_builder<T>(values: Vec<&T::Native>)
682    where
683        T: ByteArrayType,
684        <T as ByteArrayType>::Native: PartialEq,
685        <T as ByteArrayType>::Native: AsRef<<T as ByteArrayType>::Native>,
686    {
687        let mut builder = GenericByteDictionaryBuilder::<Int8Type, T>::new();
688        builder.append(values[0]).unwrap();
689        builder.append_null();
690        builder.append(values[1]).unwrap();
691        builder.append(values[1]).unwrap();
692        builder.append(values[0]).unwrap();
693        let array = builder.finish();
694
695        assert_eq!(
696            array.keys(),
697            &Int8Array::from(vec![Some(0), None, Some(1), Some(1), Some(0)])
698        );
699
700        // Values are polymorphic and so require a downcast.
701        let av = array.values();
702        let ava: &GenericByteArray<T> = av.as_any().downcast_ref::<GenericByteArray<T>>().unwrap();
703
704        assert_eq!(*ava.value(0), *values[0]);
705        assert_eq!(*ava.value(1), *values[1]);
706    }
707
708    #[test]
709    fn test_string_dictionary_builder() {
710        test_bytes_dictionary_builder::<GenericStringType<i32>>(vec!["abc", "def"]);
711    }
712
713    #[test]
714    fn test_binary_dictionary_builder() {
715        test_bytes_dictionary_builder::<GenericBinaryType<i32>>(vec![b"abc", b"def"]);
716    }
717
718    #[test]
719    fn test_with_capacity_presizes_dedup() {
720        // `with_capacity` must size the dedup `HashTable` from `value_capacity`,
721        // otherwise the first inserts force a chain of resize+rehash cycles.
722        let value_capacity = 128;
723        let builder =
724            GenericByteDictionaryBuilder::<Int32Type, GenericStringType<i32>>::with_capacity(
725                256,
726                value_capacity,
727                value_capacity * 32,
728            );
729        assert!(
730            builder.dedup.capacity() >= value_capacity,
731            "dedup HashTable not pre-sized: got capacity {}, expected >= {}",
732            builder.dedup.capacity(),
733            value_capacity,
734        );
735    }
736
737    fn test_bytes_dictionary_builder_finish_cloned<T>(values: Vec<&T::Native>)
738    where
739        T: ByteArrayType,
740        <T as ByteArrayType>::Native: PartialEq,
741        <T as ByteArrayType>::Native: AsRef<<T as ByteArrayType>::Native>,
742    {
743        let mut builder = GenericByteDictionaryBuilder::<Int8Type, T>::new();
744
745        builder.append(values[0]).unwrap();
746        builder.append_null();
747        builder.append(values[1]).unwrap();
748        builder.append(values[1]).unwrap();
749        builder.append(values[0]).unwrap();
750        let mut array = builder.finish_cloned();
751
752        assert_eq!(
753            array.keys(),
754            &Int8Array::from(vec![Some(0), None, Some(1), Some(1), Some(0)])
755        );
756
757        // Values are polymorphic and so require a downcast.
758        let av = array.values();
759        let ava: &GenericByteArray<T> = av.as_any().downcast_ref::<GenericByteArray<T>>().unwrap();
760
761        assert_eq!(ava.value(0), values[0]);
762        assert_eq!(ava.value(1), values[1]);
763
764        builder.append(values[0]).unwrap();
765        builder.append(values[2]).unwrap();
766        builder.append(values[1]).unwrap();
767
768        array = builder.finish();
769
770        assert_eq!(
771            array.keys(),
772            &Int8Array::from(vec![
773                Some(0),
774                None,
775                Some(1),
776                Some(1),
777                Some(0),
778                Some(0),
779                Some(2),
780                Some(1)
781            ])
782        );
783
784        // Values are polymorphic and so require a downcast.
785        let av2 = array.values();
786        let ava2: &GenericByteArray<T> =
787            av2.as_any().downcast_ref::<GenericByteArray<T>>().unwrap();
788
789        assert_eq!(ava2.value(0), values[0]);
790        assert_eq!(ava2.value(1), values[1]);
791        assert_eq!(ava2.value(2), values[2]);
792    }
793
794    #[test]
795    fn test_string_dictionary_builder_finish_cloned() {
796        test_bytes_dictionary_builder_finish_cloned::<GenericStringType<i32>>(vec![
797            "abc", "def", "ghi",
798        ]);
799    }
800
801    #[test]
802    fn test_binary_dictionary_builder_finish_cloned() {
803        test_bytes_dictionary_builder_finish_cloned::<GenericBinaryType<i32>>(vec![
804            b"abc", b"def", b"ghi",
805        ]);
806    }
807
808    fn _test_try_new_from_builder_generic_for_key_types<K1, K2, T>(values: Vec<&T::Native>)
809    where
810        K1: ArrowDictionaryKeyType,
811        K1::Native: NumCast,
812        K2: ArrowDictionaryKeyType,
813        K2::Native: NumCast + From<u8>,
814        T: ByteArrayType,
815        <T as ByteArrayType>::Native: PartialEq + AsRef<<T as ByteArrayType>::Native>,
816    {
817        let mut source = GenericByteDictionaryBuilder::<K1, T>::new();
818        source.append(values[0]).unwrap();
819        source.append(values[1]).unwrap();
820        source.append_null();
821        source.append(values[2]).unwrap();
822
823        let mut result =
824            GenericByteDictionaryBuilder::<K2, T>::try_new_from_builder(source).unwrap();
825        let array = result.finish();
826
827        let mut expected_keys_builder = PrimitiveBuilder::<K2>::new();
828        expected_keys_builder
829            .append_value(<<K2 as ArrowPrimitiveType>::Native as From<u8>>::from(0u8));
830        expected_keys_builder
831            .append_value(<<K2 as ArrowPrimitiveType>::Native as From<u8>>::from(1u8));
832        expected_keys_builder.append_null();
833        expected_keys_builder
834            .append_value(<<K2 as ArrowPrimitiveType>::Native as From<u8>>::from(2u8));
835        let expected_keys = expected_keys_builder.finish();
836        assert_eq!(array.keys(), &expected_keys);
837
838        let av = array.values();
839        let ava: &GenericByteArray<T> = av.as_any().downcast_ref::<GenericByteArray<T>>().unwrap();
840        assert_eq!(ava.value(0), values[0]);
841        assert_eq!(ava.value(1), values[1]);
842        assert_eq!(ava.value(2), values[2]);
843    }
844
845    fn test_try_new_from_builder<T>(values: Vec<&T::Native>)
846    where
847        T: ByteArrayType,
848        <T as ByteArrayType>::Native: PartialEq + AsRef<<T as ByteArrayType>::Native>,
849    {
850        // test cast to bigger size unsigned
851        _test_try_new_from_builder_generic_for_key_types::<UInt8Type, UInt16Type, T>(
852            values.clone(),
853        );
854        // test cast going to smaller size unsigned
855        _test_try_new_from_builder_generic_for_key_types::<UInt16Type, UInt8Type, T>(
856            values.clone(),
857        );
858        // test cast going to bigger size signed
859        _test_try_new_from_builder_generic_for_key_types::<Int8Type, Int16Type, T>(values.clone());
860        // test cast going to smaller size signed
861        _test_try_new_from_builder_generic_for_key_types::<Int32Type, Int16Type, T>(values.clone());
862        // test going from signed to signed for different size changes
863        _test_try_new_from_builder_generic_for_key_types::<UInt8Type, Int16Type, T>(values.clone());
864        _test_try_new_from_builder_generic_for_key_types::<Int8Type, UInt8Type, T>(values.clone());
865        _test_try_new_from_builder_generic_for_key_types::<Int8Type, UInt16Type, T>(values.clone());
866        _test_try_new_from_builder_generic_for_key_types::<Int32Type, Int16Type, T>(values.clone());
867    }
868
869    #[test]
870    fn test_string_dictionary_builder_try_new_from_builder() {
871        test_try_new_from_builder::<GenericStringType<i32>>(vec!["abc", "def", "ghi"]);
872    }
873
874    #[test]
875    fn test_binary_dictionary_builder_try_new_from_builder() {
876        test_try_new_from_builder::<GenericBinaryType<i32>>(vec![b"abc", b"def", b"ghi"]);
877    }
878
879    #[test]
880    fn test_try_new_from_builder_cast_fails() {
881        let mut source_builder = StringDictionaryBuilder::<UInt16Type>::new();
882        for i in 0..257 {
883            source_builder.append_value(format!("val{i}"));
884        }
885
886        // there should be too many values that we can't downcast to the underlying type
887        // we have keys that wouldn't fit into UInt8Type
888        let result = StringDictionaryBuilder::<UInt8Type>::try_new_from_builder(source_builder);
889        assert!(result.is_err());
890        if let Err(e) = result {
891            assert!(matches!(e, ArrowError::CastError(_)));
892            assert_eq!(
893                e.to_string(),
894                "Cast error: Can't cast dictionary keys from source type UInt16 to type UInt8"
895            );
896        }
897    }
898
899    fn test_bytes_dictionary_builder_with_existing_dictionary<T>(
900        dictionary: GenericByteArray<T>,
901        values: Vec<&T::Native>,
902    ) where
903        T: ByteArrayType,
904        <T as ByteArrayType>::Native: PartialEq,
905        <T as ByteArrayType>::Native: AsRef<<T as ByteArrayType>::Native>,
906    {
907        let mut builder =
908            GenericByteDictionaryBuilder::<Int8Type, T>::new_with_dictionary(6, &dictionary)
909                .unwrap();
910        builder.append(values[0]).unwrap();
911        builder.append_null();
912        builder.append(values[1]).unwrap();
913        builder.append(values[1]).unwrap();
914        builder.append(values[0]).unwrap();
915        builder.append(values[2]).unwrap();
916        let array = builder.finish();
917
918        assert_eq!(
919            array.keys(),
920            &Int8Array::from(vec![Some(2), None, Some(1), Some(1), Some(2), Some(3)])
921        );
922
923        // Values are polymorphic and so require a downcast.
924        let av = array.values();
925        let ava: &GenericByteArray<T> = av.as_any().downcast_ref::<GenericByteArray<T>>().unwrap();
926
927        assert!(!ava.is_valid(0));
928        assert_eq!(ava.value(1), values[1]);
929        assert_eq!(ava.value(2), values[0]);
930        assert_eq!(ava.value(3), values[2]);
931    }
932
933    #[test]
934    fn test_string_dictionary_builder_with_existing_dictionary() {
935        test_bytes_dictionary_builder_with_existing_dictionary::<GenericStringType<i32>>(
936            StringArray::from(vec![None, Some("def"), Some("abc")]),
937            vec!["abc", "def", "ghi"],
938        );
939    }
940
941    #[test]
942    fn test_binary_dictionary_builder_with_existing_dictionary() {
943        let values: Vec<Option<&[u8]>> = vec![None, Some(b"def"), Some(b"abc")];
944        test_bytes_dictionary_builder_with_existing_dictionary::<GenericBinaryType<i32>>(
945            BinaryArray::from(values),
946            vec![b"abc", b"def", b"ghi"],
947        );
948    }
949
950    fn test_bytes_dictionary_builder_with_reserved_null_value<T>(
951        dictionary: GenericByteArray<T>,
952        values: Vec<&T::Native>,
953    ) where
954        T: ByteArrayType,
955        <T as ByteArrayType>::Native: PartialEq,
956        <T as ByteArrayType>::Native: AsRef<<T as ByteArrayType>::Native>,
957    {
958        let mut builder =
959            GenericByteDictionaryBuilder::<Int16Type, T>::new_with_dictionary(4, &dictionary)
960                .unwrap();
961        builder.append(values[0]).unwrap();
962        builder.append_null();
963        builder.append(values[1]).unwrap();
964        builder.append(values[0]).unwrap();
965        let array = builder.finish();
966
967        assert!(array.is_null(1));
968        assert!(!array.is_valid(1));
969
970        let keys = array.keys();
971
972        assert_eq!(keys.value(0), 1);
973        assert!(keys.is_null(1));
974        // zero initialization is currently guaranteed by Buffer allocation and resizing
975        assert_eq!(keys.value(1), 0);
976        assert_eq!(keys.value(2), 2);
977        assert_eq!(keys.value(3), 1);
978    }
979
980    #[test]
981    fn test_string_dictionary_builder_with_reserved_null_value() {
982        let v: Vec<Option<&str>> = vec![None];
983        test_bytes_dictionary_builder_with_reserved_null_value::<GenericStringType<i32>>(
984            StringArray::from(v),
985            vec!["abc", "def"],
986        );
987    }
988
989    #[test]
990    fn test_binary_dictionary_builder_with_reserved_null_value() {
991        let values: Vec<Option<&[u8]>> = vec![None];
992        test_bytes_dictionary_builder_with_reserved_null_value::<GenericBinaryType<i32>>(
993            BinaryArray::from(values),
994            vec![b"abc", b"def"],
995        );
996    }
997
998    #[test]
999    fn test_extend() {
1000        let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1001        builder.extend(["a", "b", "c", "a", "b", "c"].into_iter().map(Some));
1002        builder.extend(["c", "d", "a"].into_iter().map(Some));
1003        let dict = builder.finish();
1004        assert_eq!(dict.keys().values(), &[0, 1, 2, 0, 1, 2, 2, 3, 0]);
1005        assert_eq!(dict.values().len(), 4);
1006    }
1007
1008    #[test]
1009    fn test_extend_dictionary() {
1010        let some_dict = {
1011            let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1012            builder.extend(["a", "b", "c", "a", "b", "c"].into_iter().map(Some));
1013            builder.extend([None::<&str>]);
1014            builder.extend(["c", "d", "a"].into_iter().map(Some));
1015            builder.append_null();
1016            builder.finish()
1017        };
1018
1019        let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1020        builder.extend(["e", "e", "f", "e", "d"].into_iter().map(Some));
1021        builder
1022            .extend_dictionary(&some_dict.downcast_dict().unwrap())
1023            .unwrap();
1024        let dict = builder.finish();
1025
1026        assert_eq!(dict.values().len(), 6);
1027
1028        let values = dict
1029            .downcast_dict::<GenericByteArray<Utf8Type>>()
1030            .unwrap()
1031            .into_iter()
1032            .collect::<Vec<_>>();
1033
1034        assert_eq!(
1035            values,
1036            [
1037                Some("e"),
1038                Some("e"),
1039                Some("f"),
1040                Some("e"),
1041                Some("d"),
1042                Some("a"),
1043                Some("b"),
1044                Some("c"),
1045                Some("a"),
1046                Some("b"),
1047                Some("c"),
1048                None,
1049                Some("c"),
1050                Some("d"),
1051                Some("a"),
1052                None
1053            ]
1054        );
1055    }
1056    #[test]
1057    fn test_extend_dictionary_with_null_in_mapped_value() {
1058        let some_dict = {
1059            let mut values_builder = GenericByteBuilder::<Utf8Type>::new();
1060            let mut keys_builder = PrimitiveBuilder::<Int32Type>::new();
1061
1062            // Manually build a dictionary values that the mapped values have null
1063            values_builder.append_null();
1064            keys_builder.append_value(0);
1065            values_builder.append_value("I like worm hugs");
1066            keys_builder.append_value(1);
1067
1068            let values = values_builder.finish();
1069            let keys = keys_builder.finish();
1070
1071            let data_type = DataType::Dictionary(
1072                Box::new(Int32Type::DATA_TYPE),
1073                Box::new(Utf8Type::DATA_TYPE),
1074            );
1075
1076            let builder = keys
1077                .into_data()
1078                .into_builder()
1079                .data_type(data_type)
1080                .child_data(vec![values.into_data()]);
1081
1082            DictionaryArray::from(unsafe { builder.build_unchecked() })
1083        };
1084
1085        let some_dict_values = some_dict.values().as_string::<i32>();
1086        assert_eq!(
1087            some_dict_values.into_iter().collect::<Vec<_>>(),
1088            &[None, Some("I like worm hugs")]
1089        );
1090
1091        let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1092        builder
1093            .extend_dictionary(&some_dict.downcast_dict().unwrap())
1094            .unwrap();
1095        let dict = builder.finish();
1096
1097        assert_eq!(dict.values().len(), 1);
1098
1099        let values = dict
1100            .downcast_dict::<GenericByteArray<Utf8Type>>()
1101            .unwrap()
1102            .into_iter()
1103            .collect::<Vec<_>>();
1104
1105        assert_eq!(values, [None, Some("I like worm hugs")]);
1106    }
1107
1108    #[test]
1109    fn test_extend_all_null_dictionary() {
1110        let some_dict = {
1111            let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1112            builder.append_nulls(2);
1113            builder.finish()
1114        };
1115
1116        let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1117        builder
1118            .extend_dictionary(&some_dict.downcast_dict().unwrap())
1119            .unwrap();
1120        let dict = builder.finish();
1121
1122        assert_eq!(dict.values().len(), 0);
1123
1124        let values = dict
1125            .downcast_dict::<GenericByteArray<Utf8Type>>()
1126            .unwrap()
1127            .into_iter()
1128            .collect::<Vec<_>>();
1129
1130        assert_eq!(values, [None, None]);
1131    }
1132
1133    #[test]
1134    fn test_finish_preserve_values() {
1135        // Create the first dictionary
1136        let mut builder = GenericByteDictionaryBuilder::<Int32Type, Utf8Type>::new();
1137        builder.append("a").unwrap();
1138        builder.append("b").unwrap();
1139        builder.append("c").unwrap();
1140        let dict = builder.finish_preserve_values();
1141        assert_eq!(dict.keys().values(), &[0, 1, 2]);
1142        assert_eq!(dict.values().len(), 3);
1143        let values = dict
1144            .downcast_dict::<GenericByteArray<Utf8Type>>()
1145            .unwrap()
1146            .into_iter()
1147            .collect::<Vec<_>>();
1148        assert_eq!(values, [Some("a"), Some("b"), Some("c")]);
1149
1150        // Create a new dictionary
1151        builder.append("d").unwrap();
1152        builder.append("e").unwrap();
1153        let dict2 = builder.finish_preserve_values();
1154
1155        // Make sure the keys are assigned after the old ones and we have the
1156        // right values
1157        assert_eq!(dict2.keys().values(), &[3, 4]);
1158        let values = dict2
1159            .downcast_dict::<GenericByteArray<Utf8Type>>()
1160            .unwrap()
1161            .into_iter()
1162            .collect::<Vec<_>>();
1163        assert_eq!(values, [Some("d"), Some("e")]);
1164
1165        // Check that we have all of the expected values
1166        assert_eq!(dict2.values().len(), 5);
1167        let all_values = dict2
1168            .values()
1169            .as_any()
1170            .downcast_ref::<StringArray>()
1171            .unwrap()
1172            .into_iter()
1173            .collect::<Vec<_>>();
1174        assert_eq!(
1175            all_values,
1176            [Some("a"), Some("b"), Some("c"), Some("d"), Some("e"),]
1177        );
1178    }
1179
1180    #[test]
1181    fn test_append_array_deduplicates_repeated_values() {
1182        let input = StringArray::from(vec!["a", "b", "a", "c", "b", "a"]);
1183
1184        let mut builder = GenericByteDictionaryBuilder::<Int8Type, Utf8Type>::new();
1185        builder.append_array(&input).unwrap();
1186        let result = builder.finish();
1187
1188        let mut expected_builder = GenericByteDictionaryBuilder::<Int8Type, Utf8Type>::new();
1189        for value in &input {
1190            expected_builder.append_option(value);
1191        }
1192        let expected = expected_builder.finish();
1193
1194        assert_eq!(result.keys().values(), expected.keys().values());
1195        assert_eq!(result.values().len(), 3);
1196    }
1197
1198    #[test]
1199    fn test_append_array_dedup_across_consecutive_calls() {
1200        let first = StringArray::from(vec!["a", "b"]);
1201        let second = StringArray::from(vec!["b", "c", "a"]);
1202
1203        let mut builder = GenericByteDictionaryBuilder::<Int8Type, Utf8Type>::new();
1204        builder.append_array(&first).unwrap();
1205        builder.append_array(&second).unwrap();
1206        let result = builder.finish();
1207
1208        assert_eq!(result.keys().values(), &[0, 1, 1, 2, 0]);
1209        assert_eq!(result.values().len(), 3);
1210    }
1211
1212    #[test]
1213    fn test_append_array_preserves_null_positions() {
1214        let input = StringArray::from(vec![Some("x"), None, Some("x"), None, Some("y")]);
1215
1216        let mut builder = GenericByteDictionaryBuilder::<Int8Type, Utf8Type>::new();
1217        builder.append_array(&input).unwrap();
1218        let result = builder.finish();
1219
1220        let mut expected_builder = GenericByteDictionaryBuilder::<Int8Type, Utf8Type>::new();
1221        for value in &input {
1222            expected_builder.append_option(value);
1223        }
1224        let expected = expected_builder.finish();
1225
1226        assert_eq!(result.keys(), expected.keys());
1227        assert_eq!(result.values().len(), 2);
1228    }
1229
1230    #[test]
1231    fn test_append_array_overflow_binary() {
1232        // Int8 keys hold at most 128 distinct values (indices 0..=127).
1233        // Inserting a 129th distinct entry must return DictionaryKeyOverflowError.
1234        let distinct_values: Vec<Option<Vec<u8>>> = (0u16..=128)
1235            .map(|n| Some(n.to_string().into_bytes()))
1236            .collect();
1237        let input = BinaryArray::from_opt_vec(
1238            distinct_values
1239                .iter()
1240                .map(|v| v.as_deref())
1241                .collect::<Vec<_>>(),
1242        );
1243
1244        let mut builder = GenericByteDictionaryBuilder::<Int8Type, BinaryType>::new();
1245        let result = builder.append_array(&input);
1246        assert!(
1247            matches!(result, Err(ArrowError::DictionaryKeyOverflowError)),
1248            "expected DictionaryKeyOverflowError, got {result:?}"
1249        );
1250    }
1251}