polars_arrow/array/dictionary/
mod.rs

1use std::hash::Hash;
2use std::hint::unreachable_unchecked;
3
4use crate::bitmap::utils::{BitmapIter, ZipValidity};
5use crate::bitmap::Bitmap;
6use crate::datatypes::{ArrowDataType, IntegerType};
7use crate::scalar::{new_scalar, Scalar};
8use crate::trusted_len::TrustedLen;
9use crate::types::NativeType;
10
11mod ffi;
12pub(super) mod fmt;
13mod iterator;
14mod mutable;
15use crate::array::specification::check_indexes_unchecked;
16mod typed_iterator;
17mod value_map;
18
19pub use iterator::*;
20pub use mutable::*;
21use polars_error::{polars_bail, PolarsResult};
22
23use super::primitive::PrimitiveArray;
24use super::specification::check_indexes;
25use super::{new_empty_array, new_null_array, Array, Splitable};
26use crate::array::dictionary::typed_iterator::{
27    DictValue, DictionaryIterTyped, DictionaryValuesIterTyped,
28};
29
30/// Trait denoting [`NativeType`]s that can be used as keys of a dictionary.
31/// # Safety
32///
33/// Any implementation of this trait must ensure that `always_fits_usize` only
34/// returns `true` if all values succeeds on `value::try_into::<usize>().unwrap()`.
35pub unsafe trait DictionaryKey: NativeType + TryInto<usize> + TryFrom<usize> + Hash {
36    /// The corresponding [`IntegerType`] of this key
37    const KEY_TYPE: IntegerType;
38    const MAX_USIZE_VALUE: usize;
39
40    /// Represents this key as a `usize`.
41    ///
42    /// # Safety
43    /// The caller _must_ have checked that the value can be cast to `usize`.
44    #[inline]
45    unsafe fn as_usize(self) -> usize {
46        match self.try_into() {
47            Ok(v) => v,
48            Err(_) => unreachable_unchecked(),
49        }
50    }
51
52    /// Create a key from a `usize` without checking bounds.
53    ///
54    /// # Safety
55    /// The caller _must_ have checked that the value can be created from a `usize`.
56    #[inline]
57    unsafe fn from_usize_unchecked(x: usize) -> Self {
58        debug_assert!(Self::try_from(x).is_ok());
59        unsafe { Self::try_from(x).unwrap_unchecked() }
60    }
61
62    /// If the key type always can be converted to `usize`.
63    fn always_fits_usize() -> bool {
64        false
65    }
66}
67
68unsafe impl DictionaryKey for i8 {
69    const KEY_TYPE: IntegerType = IntegerType::Int8;
70    const MAX_USIZE_VALUE: usize = i8::MAX as usize;
71}
72unsafe impl DictionaryKey for i16 {
73    const KEY_TYPE: IntegerType = IntegerType::Int16;
74    const MAX_USIZE_VALUE: usize = i16::MAX as usize;
75}
76unsafe impl DictionaryKey for i32 {
77    const KEY_TYPE: IntegerType = IntegerType::Int32;
78    const MAX_USIZE_VALUE: usize = i32::MAX as usize;
79}
80unsafe impl DictionaryKey for i64 {
81    const KEY_TYPE: IntegerType = IntegerType::Int64;
82    const MAX_USIZE_VALUE: usize = i64::MAX as usize;
83}
84unsafe impl DictionaryKey for i128 {
85    const KEY_TYPE: IntegerType = IntegerType::Int128;
86    const MAX_USIZE_VALUE: usize = i128::MAX as usize;
87}
88unsafe impl DictionaryKey for u8 {
89    const KEY_TYPE: IntegerType = IntegerType::UInt8;
90    const MAX_USIZE_VALUE: usize = u8::MAX as usize;
91
92    fn always_fits_usize() -> bool {
93        true
94    }
95}
96unsafe impl DictionaryKey for u16 {
97    const KEY_TYPE: IntegerType = IntegerType::UInt16;
98    const MAX_USIZE_VALUE: usize = u16::MAX as usize;
99
100    fn always_fits_usize() -> bool {
101        true
102    }
103}
104unsafe impl DictionaryKey for u32 {
105    const KEY_TYPE: IntegerType = IntegerType::UInt32;
106    const MAX_USIZE_VALUE: usize = u32::MAX as usize;
107
108    fn always_fits_usize() -> bool {
109        true
110    }
111}
112unsafe impl DictionaryKey for u64 {
113    const KEY_TYPE: IntegerType = IntegerType::UInt64;
114    const MAX_USIZE_VALUE: usize = u64::MAX as usize;
115
116    #[cfg(target_pointer_width = "64")]
117    fn always_fits_usize() -> bool {
118        true
119    }
120}
121
122/// An [`Array`] whose values are stored as indices. This [`Array`] is useful when the cardinality of
123/// values is low compared to the length of the [`Array`].
124///
125/// # Safety
126/// This struct guarantees that each item of [`DictionaryArray::keys`] is castable to `usize` and
127/// its value is smaller than [`DictionaryArray::values`]`.len()`. In other words, you can safely
128/// use `unchecked` calls to retrieve the values
129#[derive(Clone)]
130pub struct DictionaryArray<K: DictionaryKey> {
131    dtype: ArrowDataType,
132    keys: PrimitiveArray<K>,
133    values: Box<dyn Array>,
134}
135
136fn check_dtype(
137    key_type: IntegerType,
138    dtype: &ArrowDataType,
139    values_dtype: &ArrowDataType,
140) -> PolarsResult<()> {
141    if let ArrowDataType::Dictionary(key, value, _) = dtype.to_logical_type() {
142        if *key != key_type {
143            polars_bail!(ComputeError: "DictionaryArray must be initialized with a DataType::Dictionary whose integer is compatible to its keys")
144        }
145        if value.as_ref().to_logical_type() != values_dtype.to_logical_type() {
146            polars_bail!(ComputeError: "DictionaryArray must be initialized with a DataType::Dictionary whose value is equal to its values")
147        }
148    } else {
149        polars_bail!(ComputeError: "DictionaryArray must be initialized with logical DataType::Dictionary")
150    }
151    Ok(())
152}
153
154impl<K: DictionaryKey> DictionaryArray<K> {
155    /// Returns a new [`DictionaryArray`].
156    /// # Implementation
157    /// This function is `O(N)` where `N` is the length of keys
158    /// # Errors
159    /// This function errors iff
160    /// * the `dtype`'s logical type is not a `DictionaryArray`
161    /// * the `dtype`'s keys is not compatible with `keys`
162    /// * the `dtype`'s values's dtype is not equal with `values.dtype()`
163    /// * any of the keys's values is not represented in `usize` or is `>= values.len()`
164    pub fn try_new(
165        dtype: ArrowDataType,
166        keys: PrimitiveArray<K>,
167        values: Box<dyn Array>,
168    ) -> PolarsResult<Self> {
169        check_dtype(K::KEY_TYPE, &dtype, values.dtype())?;
170
171        if keys.null_count() != keys.len() {
172            if K::always_fits_usize() {
173                // SAFETY: we just checked that conversion to `usize` always
174                // succeeds
175                unsafe { check_indexes_unchecked(keys.values(), values.len()) }?;
176            } else {
177                check_indexes(keys.values(), values.len())?;
178            }
179        }
180
181        Ok(Self {
182            dtype,
183            keys,
184            values,
185        })
186    }
187
188    /// Returns a new [`DictionaryArray`].
189    /// # Implementation
190    /// This function is `O(N)` where `N` is the length of keys
191    /// # Errors
192    /// This function errors iff
193    /// * any of the keys's values is not represented in `usize` or is `>= values.len()`
194    pub fn try_from_keys(keys: PrimitiveArray<K>, values: Box<dyn Array>) -> PolarsResult<Self> {
195        let dtype = Self::default_dtype(values.dtype().clone());
196        Self::try_new(dtype, keys, values)
197    }
198
199    /// Returns a new [`DictionaryArray`].
200    /// # Errors
201    /// This function errors iff
202    /// * the `dtype`'s logical type is not a `DictionaryArray`
203    /// * the `dtype`'s keys is not compatible with `keys`
204    /// * the `dtype`'s values's dtype is not equal with `values.dtype()`
205    ///
206    /// # Safety
207    /// The caller must ensure that every keys's values is represented in `usize` and is `< values.len()`
208    pub unsafe fn try_new_unchecked(
209        dtype: ArrowDataType,
210        keys: PrimitiveArray<K>,
211        values: Box<dyn Array>,
212    ) -> PolarsResult<Self> {
213        check_dtype(K::KEY_TYPE, &dtype, values.dtype())?;
214
215        Ok(Self {
216            dtype,
217            keys,
218            values,
219        })
220    }
221
222    /// Returns a new empty [`DictionaryArray`].
223    pub fn new_empty(dtype: ArrowDataType) -> Self {
224        let values = Self::try_get_child(&dtype).unwrap();
225        let values = new_empty_array(values.clone());
226        Self::try_new(
227            dtype,
228            PrimitiveArray::<K>::new_empty(K::PRIMITIVE.into()),
229            values,
230        )
231        .unwrap()
232    }
233
234    /// Returns an [`DictionaryArray`] whose all elements are null
235    #[inline]
236    pub fn new_null(dtype: ArrowDataType, length: usize) -> Self {
237        let values = Self::try_get_child(&dtype).unwrap();
238        let values = new_null_array(values.clone(), 1);
239        Self::try_new(
240            dtype,
241            PrimitiveArray::<K>::new_null(K::PRIMITIVE.into(), length),
242            values,
243        )
244        .unwrap()
245    }
246
247    /// Returns an iterator of [`Option<Box<dyn Scalar>>`].
248    /// # Implementation
249    /// This function will allocate a new [`Scalar`] per item and is usually not performant.
250    /// Consider calling `keys_iter` and `values`, downcasting `values`, and iterating over that.
251    pub fn iter(&self) -> ZipValidity<Box<dyn Scalar>, DictionaryValuesIter<K>, BitmapIter> {
252        ZipValidity::new_with_validity(DictionaryValuesIter::new(self), self.keys.validity())
253    }
254
255    /// Returns an iterator of [`Box<dyn Scalar>`]
256    /// # Implementation
257    /// This function will allocate a new [`Scalar`] per item and is usually not performant.
258    /// Consider calling `keys_iter` and `values`, downcasting `values`, and iterating over that.
259    pub fn values_iter(&self) -> DictionaryValuesIter<K> {
260        DictionaryValuesIter::new(self)
261    }
262
263    /// Returns an iterator over the values [`V::IterValue`].
264    ///
265    /// # Panics
266    ///
267    /// Panics if the keys of this [`DictionaryArray`] has any nulls.
268    /// If they do [`DictionaryArray::iter_typed`] should be used.
269    pub fn values_iter_typed<V: DictValue>(&self) -> PolarsResult<DictionaryValuesIterTyped<K, V>> {
270        let keys = &self.keys;
271        assert_eq!(keys.null_count(), 0);
272        let values = self.values.as_ref();
273        let values = V::downcast_values(values)?;
274        Ok(DictionaryValuesIterTyped::new(keys, values))
275    }
276
277    /// Returns an iterator over the optional values of  [`Option<V::IterValue>`].
278    pub fn iter_typed<V: DictValue>(&self) -> PolarsResult<DictionaryIterTyped<K, V>> {
279        let keys = &self.keys;
280        let values = self.values.as_ref();
281        let values = V::downcast_values(values)?;
282        Ok(DictionaryIterTyped::new(keys, values))
283    }
284
285    /// Returns the [`ArrowDataType`] of this [`DictionaryArray`]
286    #[inline]
287    pub fn dtype(&self) -> &ArrowDataType {
288        &self.dtype
289    }
290
291    /// Returns whether the values of this [`DictionaryArray`] are ordered
292    #[inline]
293    pub fn is_ordered(&self) -> bool {
294        match self.dtype.to_logical_type() {
295            ArrowDataType::Dictionary(_, _, is_ordered) => *is_ordered,
296            _ => unreachable!(),
297        }
298    }
299
300    pub(crate) fn default_dtype(values_datatype: ArrowDataType) -> ArrowDataType {
301        ArrowDataType::Dictionary(K::KEY_TYPE, Box::new(values_datatype), false)
302    }
303
304    /// Slices this [`DictionaryArray`].
305    /// # Panics
306    /// iff `offset + length > self.len()`.
307    pub fn slice(&mut self, offset: usize, length: usize) {
308        self.keys.slice(offset, length);
309    }
310
311    /// Slices this [`DictionaryArray`].
312    ///
313    /// # Safety
314    /// Safe iff `offset + length <= self.len()`.
315    pub unsafe fn slice_unchecked(&mut self, offset: usize, length: usize) {
316        self.keys.slice_unchecked(offset, length);
317    }
318
319    impl_sliced!();
320
321    /// Returns this [`DictionaryArray`] with a new validity.
322    /// # Panic
323    /// This function panics iff `validity.len() != self.len()`.
324    #[must_use]
325    pub fn with_validity(mut self, validity: Option<Bitmap>) -> Self {
326        self.set_validity(validity);
327        self
328    }
329
330    /// Sets the validity of the keys of this [`DictionaryArray`].
331    /// # Panics
332    /// This function panics iff `validity.len() != self.len()`.
333    pub fn set_validity(&mut self, validity: Option<Bitmap>) {
334        self.keys.set_validity(validity);
335    }
336
337    impl_into_array!();
338
339    /// Returns the length of this array
340    #[inline]
341    pub fn len(&self) -> usize {
342        self.keys.len()
343    }
344
345    /// The optional validity. Equivalent to `self.keys().validity()`.
346    #[inline]
347    pub fn validity(&self) -> Option<&Bitmap> {
348        self.keys.validity()
349    }
350
351    /// Returns the keys of the [`DictionaryArray`]. These keys can be used to fetch values
352    /// from `values`.
353    #[inline]
354    pub fn keys(&self) -> &PrimitiveArray<K> {
355        &self.keys
356    }
357
358    /// Returns an iterator of the keys' values of the [`DictionaryArray`] as `usize`
359    #[inline]
360    pub fn keys_values_iter(&self) -> impl TrustedLen<Item = usize> + Clone + '_ {
361        // SAFETY: invariant of the struct
362        self.keys.values_iter().map(|x| unsafe { x.as_usize() })
363    }
364
365    /// Returns an iterator of the keys' of the [`DictionaryArray`] as `usize`
366    #[inline]
367    pub fn keys_iter(&self) -> impl TrustedLen<Item = Option<usize>> + Clone + '_ {
368        // SAFETY: invariant of the struct
369        self.keys.iter().map(|x| x.map(|x| unsafe { x.as_usize() }))
370    }
371
372    /// Returns the keys' value of the [`DictionaryArray`] as `usize`
373    /// # Panics
374    /// This function panics iff `index >= self.len()`
375    #[inline]
376    pub fn key_value(&self, index: usize) -> usize {
377        // SAFETY: invariant of the struct
378        unsafe { self.keys.values()[index].as_usize() }
379    }
380
381    /// Returns the values of the [`DictionaryArray`].
382    #[inline]
383    pub fn values(&self) -> &Box<dyn Array> {
384        &self.values
385    }
386
387    /// Returns the value of the [`DictionaryArray`] at position `i`.
388    /// # Implementation
389    /// This function will allocate a new [`Scalar`] and is usually not performant.
390    /// Consider calling `keys` and `values`, downcasting `values`, and iterating over that.
391    /// # Panic
392    /// This function panics iff `index >= self.len()`
393    #[inline]
394    pub fn value(&self, index: usize) -> Box<dyn Scalar> {
395        // SAFETY: invariant of this struct
396        let index = unsafe { self.keys.value(index).as_usize() };
397        new_scalar(self.values.as_ref(), index)
398    }
399
400    pub(crate) fn try_get_child(dtype: &ArrowDataType) -> PolarsResult<&ArrowDataType> {
401        Ok(match dtype.to_logical_type() {
402            ArrowDataType::Dictionary(_, values, _) => values.as_ref(),
403            _ => {
404                polars_bail!(ComputeError: "Dictionaries must be initialized with DataType::Dictionary")
405            },
406        })
407    }
408
409    pub fn take(self) -> (ArrowDataType, PrimitiveArray<K>, Box<dyn Array>) {
410        (self.dtype, self.keys, self.values)
411    }
412}
413
414impl<K: DictionaryKey> Array for DictionaryArray<K> {
415    impl_common_array!();
416
417    fn validity(&self) -> Option<&Bitmap> {
418        self.keys.validity()
419    }
420
421    #[inline]
422    fn with_validity(&self, validity: Option<Bitmap>) -> Box<dyn Array> {
423        Box::new(self.clone().with_validity(validity))
424    }
425}
426
427impl<K: DictionaryKey> Splitable for DictionaryArray<K> {
428    fn check_bound(&self, offset: usize) -> bool {
429        offset < self.len()
430    }
431
432    unsafe fn _split_at_unchecked(&self, offset: usize) -> (Self, Self) {
433        let (lhs_keys, rhs_keys) = unsafe { Splitable::split_at_unchecked(&self.keys, offset) };
434
435        (
436            Self {
437                dtype: self.dtype.clone(),
438                keys: lhs_keys,
439                values: self.values.clone(),
440            },
441            Self {
442                dtype: self.dtype.clone(),
443                keys: rhs_keys,
444                values: self.values.clone(),
445            },
446        )
447    }
448}