polars_arrow/array/dictionary/
mod.rs1use std::hash::Hash;
2use std::hint::unreachable_unchecked;
3
4use crate::bitmap::Bitmap;
5use crate::bitmap::utils::{BitmapIter, ZipValidity};
6use crate::datatypes::{ArrowDataType, IntegerType};
7use crate::scalar::{Scalar, new_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::{PolarsResult, polars_bail};
22
23use super::primitive::PrimitiveArray;
24use super::specification::check_indexes;
25use super::{Array, Splitable, new_empty_array, new_null_array};
26use crate::array::dictionary::typed_iterator::{
27 DictValue, DictionaryIterTyped, DictionaryValuesIterTyped,
28};
29
30pub unsafe trait DictionaryKey: NativeType + TryInto<usize> + TryFrom<usize> + Hash {
36 const KEY_TYPE: IntegerType;
38 const MAX_USIZE_VALUE: usize;
39
40 #[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 #[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 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#[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 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 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 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 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 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 #[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 pub fn iter(
252 &self,
253 ) -> ZipValidity<Box<dyn Scalar>, DictionaryValuesIter<'_, K>, BitmapIter<'_>> {
254 ZipValidity::new_with_validity(DictionaryValuesIter::new(self), self.keys.validity())
255 }
256
257 pub fn values_iter(&self) -> DictionaryValuesIter<'_, K> {
262 DictionaryValuesIter::new(self)
263 }
264
265 pub fn values_iter_typed<V: DictValue>(
272 &self,
273 ) -> PolarsResult<DictionaryValuesIterTyped<'_, K, V>> {
274 let keys = &self.keys;
275 assert_eq!(keys.null_count(), 0);
276 let values = self.values.as_ref();
277 let values = V::downcast_values(values)?;
278 Ok(DictionaryValuesIterTyped::new(keys, values))
279 }
280
281 pub fn iter_typed<V: DictValue>(&self) -> PolarsResult<DictionaryIterTyped<'_, K, V>> {
283 let keys = &self.keys;
284 let values = self.values.as_ref();
285 let values = V::downcast_values(values)?;
286 Ok(DictionaryIterTyped::new(keys, values))
287 }
288
289 #[inline]
291 pub fn dtype(&self) -> &ArrowDataType {
292 &self.dtype
293 }
294
295 #[inline]
297 pub fn is_ordered(&self) -> bool {
298 match self.dtype.to_logical_type() {
299 ArrowDataType::Dictionary(_, _, is_ordered) => *is_ordered,
300 _ => unreachable!(),
301 }
302 }
303
304 pub(crate) fn default_dtype(values_datatype: ArrowDataType) -> ArrowDataType {
305 ArrowDataType::Dictionary(K::KEY_TYPE, Box::new(values_datatype), false)
306 }
307
308 pub fn slice(&mut self, offset: usize, length: usize) {
312 self.keys.slice(offset, length);
313 }
314
315 pub unsafe fn slice_unchecked(&mut self, offset: usize, length: usize) {
320 self.keys.slice_unchecked(offset, length);
321 }
322
323 impl_sliced!();
324
325 #[must_use]
329 pub fn with_validity(mut self, validity: Option<Bitmap>) -> Self {
330 self.set_validity(validity);
331 self
332 }
333
334 pub fn set_validity(&mut self, validity: Option<Bitmap>) {
338 self.keys.set_validity(validity);
339 }
340
341 impl_into_array!();
342
343 #[inline]
345 pub fn len(&self) -> usize {
346 self.keys.len()
347 }
348
349 #[inline]
351 pub fn validity(&self) -> Option<&Bitmap> {
352 self.keys.validity()
353 }
354
355 #[inline]
358 pub fn keys(&self) -> &PrimitiveArray<K> {
359 &self.keys
360 }
361
362 #[inline]
364 pub fn keys_values_iter(&self) -> impl TrustedLen<Item = usize> + Clone + '_ {
365 self.keys.values_iter().map(|x| unsafe { x.as_usize() })
367 }
368
369 #[inline]
371 pub fn keys_iter(&self) -> impl TrustedLen<Item = Option<usize>> + Clone + '_ {
372 self.keys.iter().map(|x| x.map(|x| unsafe { x.as_usize() }))
374 }
375
376 #[inline]
380 pub fn key_value(&self, index: usize) -> usize {
381 unsafe { self.keys.values()[index].as_usize() }
383 }
384
385 #[inline]
387 pub fn values(&self) -> &Box<dyn Array> {
388 &self.values
389 }
390
391 #[inline]
398 pub fn value(&self, index: usize) -> Box<dyn Scalar> {
399 let index = unsafe { self.keys.value(index).as_usize() };
401 new_scalar(self.values.as_ref(), index)
402 }
403
404 pub(crate) fn try_get_child(dtype: &ArrowDataType) -> PolarsResult<&ArrowDataType> {
405 Ok(match dtype.to_logical_type() {
406 ArrowDataType::Dictionary(_, values, _) => values.as_ref(),
407 _ => {
408 polars_bail!(ComputeError: "Dictionaries must be initialized with DataType::Dictionary")
409 },
410 })
411 }
412
413 pub fn take(self) -> (ArrowDataType, PrimitiveArray<K>, Box<dyn Array>) {
414 (self.dtype, self.keys, self.values)
415 }
416}
417
418impl<K: DictionaryKey> Array for DictionaryArray<K> {
419 impl_common_array!();
420
421 fn validity(&self) -> Option<&Bitmap> {
422 self.keys.validity()
423 }
424
425 #[inline]
426 fn with_validity(&self, validity: Option<Bitmap>) -> Box<dyn Array> {
427 Box::new(self.clone().with_validity(validity))
428 }
429}
430
431impl<K: DictionaryKey> Splitable for DictionaryArray<K> {
432 fn check_bound(&self, offset: usize) -> bool {
433 offset < self.len()
434 }
435
436 unsafe fn _split_at_unchecked(&self, offset: usize) -> (Self, Self) {
437 let (lhs_keys, rhs_keys) = unsafe { Splitable::split_at_unchecked(&self.keys, offset) };
438
439 (
440 Self {
441 dtype: self.dtype.clone(),
442 keys: lhs_keys,
443 values: self.values.clone(),
444 },
445 Self {
446 dtype: self.dtype.clone(),
447 keys: rhs_keys,
448 values: self.values.clone(),
449 },
450 )
451 }
452}