Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-arrow/src/array/dictionary/mod.rs
6939 views
1
use std::hash::Hash;
2
use std::hint::unreachable_unchecked;
3
4
use crate::bitmap::Bitmap;
5
use crate::bitmap::utils::{BitmapIter, ZipValidity};
6
use crate::datatypes::{ArrowDataType, IntegerType};
7
use crate::scalar::{Scalar, new_scalar};
8
use crate::trusted_len::TrustedLen;
9
use crate::types::NativeType;
10
11
mod ffi;
12
pub(super) mod fmt;
13
mod iterator;
14
mod mutable;
15
use crate::array::specification::check_indexes_unchecked;
16
mod typed_iterator;
17
mod value_map;
18
19
pub use iterator::*;
20
pub use mutable::*;
21
use polars_error::{PolarsResult, polars_bail};
22
23
use super::primitive::PrimitiveArray;
24
use super::specification::check_indexes;
25
use super::{Array, Splitable, new_empty_array, new_null_array};
26
use 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()`.
35
pub 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
68
unsafe impl DictionaryKey for i8 {
69
const KEY_TYPE: IntegerType = IntegerType::Int8;
70
const MAX_USIZE_VALUE: usize = i8::MAX as usize;
71
}
72
unsafe impl DictionaryKey for i16 {
73
const KEY_TYPE: IntegerType = IntegerType::Int16;
74
const MAX_USIZE_VALUE: usize = i16::MAX as usize;
75
}
76
unsafe impl DictionaryKey for i32 {
77
const KEY_TYPE: IntegerType = IntegerType::Int32;
78
const MAX_USIZE_VALUE: usize = i32::MAX as usize;
79
}
80
unsafe impl DictionaryKey for i64 {
81
const KEY_TYPE: IntegerType = IntegerType::Int64;
82
const MAX_USIZE_VALUE: usize = i64::MAX as usize;
83
}
84
unsafe impl DictionaryKey for i128 {
85
const KEY_TYPE: IntegerType = IntegerType::Int128;
86
const MAX_USIZE_VALUE: usize = i128::MAX as usize;
87
}
88
unsafe 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
}
96
unsafe 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
}
104
unsafe 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
}
112
unsafe 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)]
130
pub struct DictionaryArray<K: DictionaryKey> {
131
dtype: ArrowDataType,
132
keys: PrimitiveArray<K>,
133
values: Box<dyn Array>,
134
}
135
136
fn 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
154
impl<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(
252
&self,
253
) -> ZipValidity<Box<dyn Scalar>, DictionaryValuesIter<'_, K>, BitmapIter<'_>> {
254
ZipValidity::new_with_validity(DictionaryValuesIter::new(self), self.keys.validity())
255
}
256
257
/// Returns an iterator of [`Box<dyn Scalar>`]
258
/// # Implementation
259
/// This function will allocate a new [`Scalar`] per item and is usually not performant.
260
/// Consider calling `keys_iter` and `values`, downcasting `values`, and iterating over that.
261
pub fn values_iter(&self) -> DictionaryValuesIter<'_, K> {
262
DictionaryValuesIter::new(self)
263
}
264
265
/// Returns an iterator over the values [`V::IterValue`].
266
///
267
/// # Panics
268
///
269
/// Panics if the keys of this [`DictionaryArray`] has any nulls.
270
/// If they do [`DictionaryArray::iter_typed`] should be used.
271
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
/// Returns an iterator over the optional values of [`Option<V::IterValue>`].
282
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
/// Returns the [`ArrowDataType`] of this [`DictionaryArray`]
290
#[inline]
291
pub fn dtype(&self) -> &ArrowDataType {
292
&self.dtype
293
}
294
295
/// Returns whether the values of this [`DictionaryArray`] are ordered
296
#[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
/// Slices this [`DictionaryArray`].
309
/// # Panics
310
/// iff `offset + length > self.len()`.
311
pub fn slice(&mut self, offset: usize, length: usize) {
312
self.keys.slice(offset, length);
313
}
314
315
/// Slices this [`DictionaryArray`].
316
///
317
/// # Safety
318
/// Safe iff `offset + length <= self.len()`.
319
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
/// Returns this [`DictionaryArray`] with a new validity.
326
/// # Panic
327
/// This function panics iff `validity.len() != self.len()`.
328
#[must_use]
329
pub fn with_validity(mut self, validity: Option<Bitmap>) -> Self {
330
self.set_validity(validity);
331
self
332
}
333
334
/// Sets the validity of the keys of this [`DictionaryArray`].
335
/// # Panics
336
/// This function panics iff `validity.len() != self.len()`.
337
pub fn set_validity(&mut self, validity: Option<Bitmap>) {
338
self.keys.set_validity(validity);
339
}
340
341
impl_into_array!();
342
343
/// Returns the length of this array
344
#[inline]
345
pub fn len(&self) -> usize {
346
self.keys.len()
347
}
348
349
/// The optional validity. Equivalent to `self.keys().validity()`.
350
#[inline]
351
pub fn validity(&self) -> Option<&Bitmap> {
352
self.keys.validity()
353
}
354
355
/// Returns the keys of the [`DictionaryArray`]. These keys can be used to fetch values
356
/// from `values`.
357
#[inline]
358
pub fn keys(&self) -> &PrimitiveArray<K> {
359
&self.keys
360
}
361
362
/// Returns an iterator of the keys' values of the [`DictionaryArray`] as `usize`
363
#[inline]
364
pub fn keys_values_iter(&self) -> impl TrustedLen<Item = usize> + Clone + '_ {
365
// SAFETY: invariant of the struct
366
self.keys.values_iter().map(|x| unsafe { x.as_usize() })
367
}
368
369
/// Returns an iterator of the keys' of the [`DictionaryArray`] as `usize`
370
#[inline]
371
pub fn keys_iter(&self) -> impl TrustedLen<Item = Option<usize>> + Clone + '_ {
372
// SAFETY: invariant of the struct
373
self.keys.iter().map(|x| x.map(|x| unsafe { x.as_usize() }))
374
}
375
376
/// Returns the keys' value of the [`DictionaryArray`] as `usize`
377
/// # Panics
378
/// This function panics iff `index >= self.len()`
379
#[inline]
380
pub fn key_value(&self, index: usize) -> usize {
381
// SAFETY: invariant of the struct
382
unsafe { self.keys.values()[index].as_usize() }
383
}
384
385
/// Returns the values of the [`DictionaryArray`].
386
#[inline]
387
pub fn values(&self) -> &Box<dyn Array> {
388
&self.values
389
}
390
391
/// Returns the value of the [`DictionaryArray`] at position `i`.
392
/// # Implementation
393
/// This function will allocate a new [`Scalar`] and is usually not performant.
394
/// Consider calling `keys` and `values`, downcasting `values`, and iterating over that.
395
/// # Panic
396
/// This function panics iff `index >= self.len()`
397
#[inline]
398
pub fn value(&self, index: usize) -> Box<dyn Scalar> {
399
// SAFETY: invariant of this struct
400
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
418
impl<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
431
impl<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
}
453
454