Path: blob/main/crates/polars-arrow/src/array/dictionary/mod.rs
6939 views
use std::hash::Hash;1use std::hint::unreachable_unchecked;23use crate::bitmap::Bitmap;4use crate::bitmap::utils::{BitmapIter, ZipValidity};5use crate::datatypes::{ArrowDataType, IntegerType};6use crate::scalar::{Scalar, new_scalar};7use crate::trusted_len::TrustedLen;8use crate::types::NativeType;910mod ffi;11pub(super) mod fmt;12mod iterator;13mod mutable;14use crate::array::specification::check_indexes_unchecked;15mod typed_iterator;16mod value_map;1718pub use iterator::*;19pub use mutable::*;20use polars_error::{PolarsResult, polars_bail};2122use super::primitive::PrimitiveArray;23use super::specification::check_indexes;24use super::{Array, Splitable, new_empty_array, new_null_array};25use crate::array::dictionary::typed_iterator::{26DictValue, DictionaryIterTyped, DictionaryValuesIterTyped,27};2829/// Trait denoting [`NativeType`]s that can be used as keys of a dictionary.30/// # Safety31///32/// Any implementation of this trait must ensure that `always_fits_usize` only33/// returns `true` if all values succeeds on `value::try_into::<usize>().unwrap()`.34pub unsafe trait DictionaryKey: NativeType + TryInto<usize> + TryFrom<usize> + Hash {35/// The corresponding [`IntegerType`] of this key36const KEY_TYPE: IntegerType;37const MAX_USIZE_VALUE: usize;3839/// Represents this key as a `usize`.40///41/// # Safety42/// The caller _must_ have checked that the value can be cast to `usize`.43#[inline]44unsafe fn as_usize(self) -> usize {45match self.try_into() {46Ok(v) => v,47Err(_) => unreachable_unchecked(),48}49}5051/// Create a key from a `usize` without checking bounds.52///53/// # Safety54/// The caller _must_ have checked that the value can be created from a `usize`.55#[inline]56unsafe fn from_usize_unchecked(x: usize) -> Self {57debug_assert!(Self::try_from(x).is_ok());58unsafe { Self::try_from(x).unwrap_unchecked() }59}6061/// If the key type always can be converted to `usize`.62fn always_fits_usize() -> bool {63false64}65}6667unsafe impl DictionaryKey for i8 {68const KEY_TYPE: IntegerType = IntegerType::Int8;69const MAX_USIZE_VALUE: usize = i8::MAX as usize;70}71unsafe impl DictionaryKey for i16 {72const KEY_TYPE: IntegerType = IntegerType::Int16;73const MAX_USIZE_VALUE: usize = i16::MAX as usize;74}75unsafe impl DictionaryKey for i32 {76const KEY_TYPE: IntegerType = IntegerType::Int32;77const MAX_USIZE_VALUE: usize = i32::MAX as usize;78}79unsafe impl DictionaryKey for i64 {80const KEY_TYPE: IntegerType = IntegerType::Int64;81const MAX_USIZE_VALUE: usize = i64::MAX as usize;82}83unsafe impl DictionaryKey for i128 {84const KEY_TYPE: IntegerType = IntegerType::Int128;85const MAX_USIZE_VALUE: usize = i128::MAX as usize;86}87unsafe impl DictionaryKey for u8 {88const KEY_TYPE: IntegerType = IntegerType::UInt8;89const MAX_USIZE_VALUE: usize = u8::MAX as usize;9091fn always_fits_usize() -> bool {92true93}94}95unsafe impl DictionaryKey for u16 {96const KEY_TYPE: IntegerType = IntegerType::UInt16;97const MAX_USIZE_VALUE: usize = u16::MAX as usize;9899fn always_fits_usize() -> bool {100true101}102}103unsafe impl DictionaryKey for u32 {104const KEY_TYPE: IntegerType = IntegerType::UInt32;105const MAX_USIZE_VALUE: usize = u32::MAX as usize;106107fn always_fits_usize() -> bool {108true109}110}111unsafe impl DictionaryKey for u64 {112const KEY_TYPE: IntegerType = IntegerType::UInt64;113const MAX_USIZE_VALUE: usize = u64::MAX as usize;114115#[cfg(target_pointer_width = "64")]116fn always_fits_usize() -> bool {117true118}119}120121/// An [`Array`] whose values are stored as indices. This [`Array`] is useful when the cardinality of122/// values is low compared to the length of the [`Array`].123///124/// # Safety125/// This struct guarantees that each item of [`DictionaryArray::keys`] is castable to `usize` and126/// its value is smaller than [`DictionaryArray::values`]`.len()`. In other words, you can safely127/// use `unchecked` calls to retrieve the values128#[derive(Clone)]129pub struct DictionaryArray<K: DictionaryKey> {130dtype: ArrowDataType,131keys: PrimitiveArray<K>,132values: Box<dyn Array>,133}134135fn check_dtype(136key_type: IntegerType,137dtype: &ArrowDataType,138values_dtype: &ArrowDataType,139) -> PolarsResult<()> {140if let ArrowDataType::Dictionary(key, value, _) = dtype.to_logical_type() {141if *key != key_type {142polars_bail!(ComputeError: "DictionaryArray must be initialized with a DataType::Dictionary whose integer is compatible to its keys")143}144if value.as_ref().to_logical_type() != values_dtype.to_logical_type() {145polars_bail!(ComputeError: "DictionaryArray must be initialized with a DataType::Dictionary whose value is equal to its values")146}147} else {148polars_bail!(ComputeError: "DictionaryArray must be initialized with logical DataType::Dictionary")149}150Ok(())151}152153impl<K: DictionaryKey> DictionaryArray<K> {154/// Returns a new [`DictionaryArray`].155/// # Implementation156/// This function is `O(N)` where `N` is the length of keys157/// # Errors158/// This function errors iff159/// * the `dtype`'s logical type is not a `DictionaryArray`160/// * the `dtype`'s keys is not compatible with `keys`161/// * the `dtype`'s values's dtype is not equal with `values.dtype()`162/// * any of the keys's values is not represented in `usize` or is `>= values.len()`163pub fn try_new(164dtype: ArrowDataType,165keys: PrimitiveArray<K>,166values: Box<dyn Array>,167) -> PolarsResult<Self> {168check_dtype(K::KEY_TYPE, &dtype, values.dtype())?;169170if keys.null_count() != keys.len() {171if K::always_fits_usize() {172// SAFETY: we just checked that conversion to `usize` always173// succeeds174unsafe { check_indexes_unchecked(keys.values(), values.len()) }?;175} else {176check_indexes(keys.values(), values.len())?;177}178}179180Ok(Self {181dtype,182keys,183values,184})185}186187/// Returns a new [`DictionaryArray`].188/// # Implementation189/// This function is `O(N)` where `N` is the length of keys190/// # Errors191/// This function errors iff192/// * any of the keys's values is not represented in `usize` or is `>= values.len()`193pub fn try_from_keys(keys: PrimitiveArray<K>, values: Box<dyn Array>) -> PolarsResult<Self> {194let dtype = Self::default_dtype(values.dtype().clone());195Self::try_new(dtype, keys, values)196}197198/// Returns a new [`DictionaryArray`].199/// # Errors200/// This function errors iff201/// * the `dtype`'s logical type is not a `DictionaryArray`202/// * the `dtype`'s keys is not compatible with `keys`203/// * the `dtype`'s values's dtype is not equal with `values.dtype()`204///205/// # Safety206/// The caller must ensure that every keys's values is represented in `usize` and is `< values.len()`207pub unsafe fn try_new_unchecked(208dtype: ArrowDataType,209keys: PrimitiveArray<K>,210values: Box<dyn Array>,211) -> PolarsResult<Self> {212check_dtype(K::KEY_TYPE, &dtype, values.dtype())?;213214Ok(Self {215dtype,216keys,217values,218})219}220221/// Returns a new empty [`DictionaryArray`].222pub fn new_empty(dtype: ArrowDataType) -> Self {223let values = Self::try_get_child(&dtype).unwrap();224let values = new_empty_array(values.clone());225Self::try_new(226dtype,227PrimitiveArray::<K>::new_empty(K::PRIMITIVE.into()),228values,229)230.unwrap()231}232233/// Returns an [`DictionaryArray`] whose all elements are null234#[inline]235pub fn new_null(dtype: ArrowDataType, length: usize) -> Self {236let values = Self::try_get_child(&dtype).unwrap();237let values = new_null_array(values.clone(), 1);238Self::try_new(239dtype,240PrimitiveArray::<K>::new_null(K::PRIMITIVE.into(), length),241values,242)243.unwrap()244}245246/// Returns an iterator of [`Option<Box<dyn Scalar>>`].247/// # Implementation248/// This function will allocate a new [`Scalar`] per item and is usually not performant.249/// Consider calling `keys_iter` and `values`, downcasting `values`, and iterating over that.250pub fn iter(251&self,252) -> ZipValidity<Box<dyn Scalar>, DictionaryValuesIter<'_, K>, BitmapIter<'_>> {253ZipValidity::new_with_validity(DictionaryValuesIter::new(self), self.keys.validity())254}255256/// Returns an iterator of [`Box<dyn Scalar>`]257/// # Implementation258/// This function will allocate a new [`Scalar`] per item and is usually not performant.259/// Consider calling `keys_iter` and `values`, downcasting `values`, and iterating over that.260pub fn values_iter(&self) -> DictionaryValuesIter<'_, K> {261DictionaryValuesIter::new(self)262}263264/// Returns an iterator over the values [`V::IterValue`].265///266/// # Panics267///268/// Panics if the keys of this [`DictionaryArray`] has any nulls.269/// If they do [`DictionaryArray::iter_typed`] should be used.270pub fn values_iter_typed<V: DictValue>(271&self,272) -> PolarsResult<DictionaryValuesIterTyped<'_, K, V>> {273let keys = &self.keys;274assert_eq!(keys.null_count(), 0);275let values = self.values.as_ref();276let values = V::downcast_values(values)?;277Ok(DictionaryValuesIterTyped::new(keys, values))278}279280/// Returns an iterator over the optional values of [`Option<V::IterValue>`].281pub fn iter_typed<V: DictValue>(&self) -> PolarsResult<DictionaryIterTyped<'_, K, V>> {282let keys = &self.keys;283let values = self.values.as_ref();284let values = V::downcast_values(values)?;285Ok(DictionaryIterTyped::new(keys, values))286}287288/// Returns the [`ArrowDataType`] of this [`DictionaryArray`]289#[inline]290pub fn dtype(&self) -> &ArrowDataType {291&self.dtype292}293294/// Returns whether the values of this [`DictionaryArray`] are ordered295#[inline]296pub fn is_ordered(&self) -> bool {297match self.dtype.to_logical_type() {298ArrowDataType::Dictionary(_, _, is_ordered) => *is_ordered,299_ => unreachable!(),300}301}302303pub(crate) fn default_dtype(values_datatype: ArrowDataType) -> ArrowDataType {304ArrowDataType::Dictionary(K::KEY_TYPE, Box::new(values_datatype), false)305}306307/// Slices this [`DictionaryArray`].308/// # Panics309/// iff `offset + length > self.len()`.310pub fn slice(&mut self, offset: usize, length: usize) {311self.keys.slice(offset, length);312}313314/// Slices this [`DictionaryArray`].315///316/// # Safety317/// Safe iff `offset + length <= self.len()`.318pub unsafe fn slice_unchecked(&mut self, offset: usize, length: usize) {319self.keys.slice_unchecked(offset, length);320}321322impl_sliced!();323324/// Returns this [`DictionaryArray`] with a new validity.325/// # Panic326/// This function panics iff `validity.len() != self.len()`.327#[must_use]328pub fn with_validity(mut self, validity: Option<Bitmap>) -> Self {329self.set_validity(validity);330self331}332333/// Sets the validity of the keys of this [`DictionaryArray`].334/// # Panics335/// This function panics iff `validity.len() != self.len()`.336pub fn set_validity(&mut self, validity: Option<Bitmap>) {337self.keys.set_validity(validity);338}339340impl_into_array!();341342/// Returns the length of this array343#[inline]344pub fn len(&self) -> usize {345self.keys.len()346}347348/// The optional validity. Equivalent to `self.keys().validity()`.349#[inline]350pub fn validity(&self) -> Option<&Bitmap> {351self.keys.validity()352}353354/// Returns the keys of the [`DictionaryArray`]. These keys can be used to fetch values355/// from `values`.356#[inline]357pub fn keys(&self) -> &PrimitiveArray<K> {358&self.keys359}360361/// Returns an iterator of the keys' values of the [`DictionaryArray`] as `usize`362#[inline]363pub fn keys_values_iter(&self) -> impl TrustedLen<Item = usize> + Clone + '_ {364// SAFETY: invariant of the struct365self.keys.values_iter().map(|x| unsafe { x.as_usize() })366}367368/// Returns an iterator of the keys' of the [`DictionaryArray`] as `usize`369#[inline]370pub fn keys_iter(&self) -> impl TrustedLen<Item = Option<usize>> + Clone + '_ {371// SAFETY: invariant of the struct372self.keys.iter().map(|x| x.map(|x| unsafe { x.as_usize() }))373}374375/// Returns the keys' value of the [`DictionaryArray`] as `usize`376/// # Panics377/// This function panics iff `index >= self.len()`378#[inline]379pub fn key_value(&self, index: usize) -> usize {380// SAFETY: invariant of the struct381unsafe { self.keys.values()[index].as_usize() }382}383384/// Returns the values of the [`DictionaryArray`].385#[inline]386pub fn values(&self) -> &Box<dyn Array> {387&self.values388}389390/// Returns the value of the [`DictionaryArray`] at position `i`.391/// # Implementation392/// This function will allocate a new [`Scalar`] and is usually not performant.393/// Consider calling `keys` and `values`, downcasting `values`, and iterating over that.394/// # Panic395/// This function panics iff `index >= self.len()`396#[inline]397pub fn value(&self, index: usize) -> Box<dyn Scalar> {398// SAFETY: invariant of this struct399let index = unsafe { self.keys.value(index).as_usize() };400new_scalar(self.values.as_ref(), index)401}402403pub(crate) fn try_get_child(dtype: &ArrowDataType) -> PolarsResult<&ArrowDataType> {404Ok(match dtype.to_logical_type() {405ArrowDataType::Dictionary(_, values, _) => values.as_ref(),406_ => {407polars_bail!(ComputeError: "Dictionaries must be initialized with DataType::Dictionary")408},409})410}411412pub fn take(self) -> (ArrowDataType, PrimitiveArray<K>, Box<dyn Array>) {413(self.dtype, self.keys, self.values)414}415}416417impl<K: DictionaryKey> Array for DictionaryArray<K> {418impl_common_array!();419420fn validity(&self) -> Option<&Bitmap> {421self.keys.validity()422}423424#[inline]425fn with_validity(&self, validity: Option<Bitmap>) -> Box<dyn Array> {426Box::new(self.clone().with_validity(validity))427}428}429430impl<K: DictionaryKey> Splitable for DictionaryArray<K> {431fn check_bound(&self, offset: usize) -> bool {432offset < self.len()433}434435unsafe fn _split_at_unchecked(&self, offset: usize) -> (Self, Self) {436let (lhs_keys, rhs_keys) = unsafe { Splitable::split_at_unchecked(&self.keys, offset) };437438(439Self {440dtype: self.dtype.clone(),441keys: lhs_keys,442values: self.values.clone(),443},444Self {445dtype: self.dtype.clone(),446keys: rhs_keys,447values: self.values.clone(),448},449)450}451}452453454