polars_arrow/array/dictionary/
mod.rs1use 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
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(&self) -> ZipValidity<Box<dyn Scalar>, DictionaryValuesIter<K>, BitmapIter> {
252 ZipValidity::new_with_validity(DictionaryValuesIter::new(self), self.keys.validity())
253 }
254
255 pub fn values_iter(&self) -> DictionaryValuesIter<K> {
260 DictionaryValuesIter::new(self)
261 }
262
263 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 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 #[inline]
287 pub fn dtype(&self) -> &ArrowDataType {
288 &self.dtype
289 }
290
291 #[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 pub fn slice(&mut self, offset: usize, length: usize) {
308 self.keys.slice(offset, length);
309 }
310
311 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 #[must_use]
325 pub fn with_validity(mut self, validity: Option<Bitmap>) -> Self {
326 self.set_validity(validity);
327 self
328 }
329
330 pub fn set_validity(&mut self, validity: Option<Bitmap>) {
334 self.keys.set_validity(validity);
335 }
336
337 impl_into_array!();
338
339 #[inline]
341 pub fn len(&self) -> usize {
342 self.keys.len()
343 }
344
345 #[inline]
347 pub fn validity(&self) -> Option<&Bitmap> {
348 self.keys.validity()
349 }
350
351 #[inline]
354 pub fn keys(&self) -> &PrimitiveArray<K> {
355 &self.keys
356 }
357
358 #[inline]
360 pub fn keys_values_iter(&self) -> impl TrustedLen<Item = usize> + Clone + '_ {
361 self.keys.values_iter().map(|x| unsafe { x.as_usize() })
363 }
364
365 #[inline]
367 pub fn keys_iter(&self) -> impl TrustedLen<Item = Option<usize>> + Clone + '_ {
368 self.keys.iter().map(|x| x.map(|x| unsafe { x.as_usize() }))
370 }
371
372 #[inline]
376 pub fn key_value(&self, index: usize) -> usize {
377 unsafe { self.keys.values()[index].as_usize() }
379 }
380
381 #[inline]
383 pub fn values(&self) -> &Box<dyn Array> {
384 &self.values
385 }
386
387 #[inline]
394 pub fn value(&self, index: usize) -> Box<dyn Scalar> {
395 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}