Skip to main content

polars_core/datatypes/
dtype.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3
4use polars_arrow::datatypes::{
5    DTYPE_CATEGORICAL_NEW, DTYPE_ENUM_VALUES_LEGACY, DTYPE_ENUM_VALUES_NEW, MAINTAIN_PL_TYPE,
6    Metadata, PL_KEY,
7};
8#[cfg(feature = "dtype-array")]
9use polars_utils::format_tuple;
10use polars_utils::itertools::Itertools;
11#[cfg(any(feature = "serde-lazy", feature = "serde"))]
12use serde::{Deserialize, Serialize};
13pub use temporal::time_zone::TimeZone;
14
15use super::*;
16#[cfg(feature = "object")]
17use crate::chunked_array::object::registry::get_object_physical_type;
18#[cfg(feature = "dtype-extension")]
19pub use crate::datatypes::extension::ExtensionTypeInstance;
20use crate::utils::materialize_dyn_int;
21
22pub trait MetaDataExt: IntoMetadata {
23    fn pl_enum_metadata(&self) -> Option<&str> {
24        let md = self.into_metadata_ref();
25        let values = md
26            .get(DTYPE_ENUM_VALUES_NEW)
27            .or_else(|| md.get(DTYPE_ENUM_VALUES_LEGACY));
28        Some(values?.as_str())
29    }
30
31    fn pl_categorical_metadata(&self) -> Option<&str> {
32        // We ignore DTYPE_CATEGORICAL_LEGACY here, as we already map all
33        // string-typed arrow dictionaries to the global Categories, and the
34        // legacy metadata format only specifies the now-removed physical
35        // ordering parameter.
36        Some(
37            self.into_metadata_ref()
38                .get(DTYPE_CATEGORICAL_NEW)?
39                .as_str(),
40        )
41    }
42
43    fn maintain_type(&self) -> bool {
44        let metadata = self.into_metadata_ref();
45        metadata.get(PL_KEY).map(|s| s.as_str()) == Some(MAINTAIN_PL_TYPE)
46    }
47}
48
49impl MetaDataExt for Metadata {}
50pub trait IntoMetadata {
51    #[allow(clippy::wrong_self_convention)]
52    fn into_metadata_ref(&self) -> &Metadata;
53}
54
55impl IntoMetadata for Metadata {
56    fn into_metadata_ref(&self) -> &Metadata {
57        self
58    }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
62#[cfg_attr(
63    any(feature = "serde", feature = "serde-lazy"),
64    derive(Serialize, Deserialize)
65)]
66#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
67pub enum UnknownKind {
68    // Hold the value to determine the concrete size.
69    Int(i128),
70    Float,
71    // Can be Categorical or String
72    Str,
73    #[default]
74    Any,
75}
76
77impl UnknownKind {
78    pub fn materialize(&self) -> Option<DataType> {
79        let dtype = match self {
80            UnknownKind::Int(v) => materialize_dyn_int(*v).dtype(),
81            UnknownKind::Float => DataType::Float64,
82            UnknownKind::Str => DataType::String,
83            UnknownKind::Any => return None,
84        };
85        Some(dtype)
86    }
87}
88
89#[derive(Clone, strum_macros::IntoStaticStr)]
90pub enum DataType {
91    Boolean,
92    UInt8,
93    UInt16,
94    UInt32,
95    UInt64,
96    UInt128,
97    Int8,
98    Int16,
99    Int32,
100    Int64,
101    Int128,
102    Float16,
103    Float32,
104    Float64,
105    /// Fixed point decimal type optional precision and non-negative scale.
106    /// This is backed by a signed 128-bit integer which allows for up to 38 significant digits.
107    /// Meaning max precision is 38.
108    #[cfg(feature = "dtype-decimal")]
109    Decimal(usize, usize), // (precision, scale), invariant: 1 <= precision <= 38.
110    /// String data
111    String,
112    Binary,
113    BinaryOffset,
114    /// A 32-bit date representing the elapsed time since UNIX epoch (1970-01-01)
115    /// in days (32 bits).
116    Date,
117    /// A 64-bit date representing the elapsed time since UNIX epoch (1970-01-01)
118    /// in the given timeunit (64 bits).
119    Datetime(TimeUnit, Option<TimeZone>),
120    /// 64-bit integer representing difference between times in milliseconds or nanoseconds
121    Duration(TimeUnit),
122    /// A 64-bit time representing the elapsed time since midnight in nanoseconds
123    Time,
124    /// A nested list with a fixed size in each row
125    #[cfg(feature = "dtype-array")]
126    Array(Box<DataType>, usize),
127    /// A nested list with a variable size in each row
128    List(Box<DataType>),
129    /// A generic type that can be used in a `Series`
130    /// &'static str can be used to determine/set inner type
131    #[cfg(feature = "object")]
132    Object(&'static str),
133    Null,
134    #[cfg(feature = "dtype-categorical")]
135    Categorical(Arc<Categories>, Arc<CategoricalMapping>),
136    // It is an Option, so that matching Enum/Categoricals can take the same guards.
137    #[cfg(feature = "dtype-categorical")]
138    Enum(Arc<FrozenCategories>, Arc<CategoricalMapping>),
139    #[cfg(feature = "dtype-struct")]
140    Struct(Vec<Field>),
141    /// A map from keys to values, keys are unique and non-null.
142    #[cfg(feature = "dtype-map")]
143    Map(Box<DataType>, Box<DataType>),
144    #[cfg(feature = "dtype-extension")]
145    Extension(ExtensionTypeInstance, Box<DataType>),
146    // some logical types we cannot know statically, e.g. Datetime
147    Unknown(UnknownKind),
148}
149
150pub trait AsRefDataType {
151    fn as_ref_dtype(&self) -> &DataType;
152}
153
154impl Hash for DataType {
155    fn hash<H: Hasher>(&self, state: &mut H) {
156        std::mem::discriminant(self).hash(state)
157    }
158}
159
160impl PartialEq for DataType {
161    #[inline]
162    fn eq(&self, other: &Self) -> bool {
163        std::mem::discriminant(self) == std::mem::discriminant(other)
164            && (!self.has_params() || self.eq_params(other))
165    }
166}
167
168impl Eq for DataType {}
169
170impl DataType {
171    /// Indicate if this dtype variant has parameters.
172    #[inline]
173    fn has_params(&self) -> bool {
174        use DataType::*;
175        match self {
176            // Types with no parameters
177            UInt8 | UInt16 | UInt32 | UInt64 | UInt128 => false,
178            Int8 | Int16 | Int32 | Int64 | Int128 => false,
179            Float16 | Float32 | Float64 => false,
180            Boolean | String | Binary | BinaryOffset => false,
181            Date | Time => false,
182            Null => false,
183
184            // Types with parameters
185            #[cfg(feature = "dtype-decimal")]
186            Decimal(..) => true,
187            Datetime(..) | Duration(..) => true,
188            #[cfg(feature = "dtype-array")]
189            Array(..) => true,
190            List(..) => true,
191            #[cfg(feature = "dtype-struct")]
192            Struct(..) => true,
193            #[cfg(feature = "dtype-map")]
194            Map(..) => true,
195            #[cfg(feature = "dtype-categorical")]
196            Categorical(..) | Enum(..) => true,
197            #[cfg(feature = "object")]
198            Object(..) => true,
199            #[cfg(feature = "dtype-extension")]
200            Extension(..) => true,
201            Unknown(..) => true,
202        }
203    }
204
205    /// Compares the parameters of data types of the same variant (see [`Self::has_params`]).
206    /// Like `has_params`, this matches every variant, so new ones must say how they compare.
207    fn eq_params(&self, other: &Self) -> bool {
208        use DataType::*;
209        debug_assert_eq!(std::mem::discriminant(self), std::mem::discriminant(other));
210        match self {
211            #[cfg(feature = "dtype-decimal")]
212            Decimal(p_l, s_l) => matches!(other, Decimal(p_r, s_r) if p_l == p_r && s_l == s_r),
213            Datetime(tu_l, tz_l) => {
214                matches!(other, Datetime(tu_r, tz_r) if tu_l == tu_r && tz_l == tz_r)
215            },
216            Duration(tu_l) => matches!(other, Duration(tu_r) if tu_l == tu_r),
217            #[cfg(feature = "dtype-array")]
218            Array(inner_l, width_l) => {
219                matches!(other, Array(inner_r, width_r) if width_l == width_r && inner_l == inner_r)
220            },
221            List(inner_l) => matches!(other, List(inner_r) if inner_l == inner_r),
222            #[cfg(feature = "dtype-map")]
223            Map(key_l, value_l) => {
224                matches!(other, Map(key_r, value_r) if key_l == key_r && value_l == value_r)
225            },
226            #[cfg(feature = "dtype-struct")]
227            Struct(fields_l) => matches!(other, Struct(fields_r) if
228                std::ptr::eq(fields_l.as_ptr(), fields_r.as_ptr()) || fields_l == fields_r),
229            #[cfg(feature = "dtype-categorical")]
230            Categorical(cats_l, _) => {
231                matches!(other, Categorical(cats_r, _) if Arc::ptr_eq(cats_l, cats_r))
232            },
233            #[cfg(feature = "dtype-categorical")]
234            Enum(fcats_l, _) => matches!(other, Enum(fcats_r, _) if Arc::ptr_eq(fcats_l, fcats_r)),
235            #[cfg(feature = "object")]
236            Object(name_l) => matches!(other, Object(name_r) if name_l == name_r),
237            #[cfg(feature = "dtype-extension")]
238            Extension(ext_l, storage_l) => matches!(other, Extension(ext_r, storage_r) if
239                ext_l == ext_r && storage_l == storage_r),
240            Unknown(l) => matches!(other, Unknown(r) if match (l, r) {
241                (UnknownKind::Int(_), UnknownKind::Int(_)) => true,
242                _ => l == r,
243            }),
244
245            // Types without parameters; `eq_params` is private and `eq` checks the
246            // dtypes before calling it, so we won't reach these cases - can return true
247            UInt8 | UInt16 | UInt32 | UInt64 | UInt128 | Int8 | Int16 | Int32 | Int64 | Int128
248            | Float16 | Float32 | Float64 | Boolean | String | Binary | BinaryOffset | Date
249            | Time | Null => true,
250        }
251    }
252}
253
254impl DataType {
255    pub const IDX_DTYPE: Self = {
256        #[cfg(not(feature = "bigidx"))]
257        {
258            DataType::UInt32
259        }
260        #[cfg(feature = "bigidx")]
261        {
262            DataType::UInt64
263        }
264    };
265
266    pub fn pretty_format(&self) -> String {
267        match self {
268            #[cfg(feature = "dtype-struct")]
269            Self::Struct(fields) => {
270                let formatted_fields = fields
271                    .iter()
272                    .map(|field| format!("{}: {}", field.name, field.dtype.pretty_format()))
273                    .collect::<Vec<String>>()
274                    .join(", ");
275                format!("struct {{{}}}", formatted_fields)
276            },
277            Self::List(inner_dtype) => {
278                let formatted_dtype = inner_dtype.pretty_format();
279                format!("list[{}]", formatted_dtype)
280            },
281            #[cfg(feature = "dtype-array")]
282            Self::Array(inner_dtype, size) => {
283                let formatted_dtype = inner_dtype.pretty_format();
284                format!("array[{}, {}]", formatted_dtype, size)
285            },
286            #[cfg(feature = "dtype-map")]
287            Self::Map(key, value) => {
288                format!("map[{}, {}]", key.pretty_format(), value.pretty_format())
289            },
290            _ => {
291                format!("{}", self)
292            },
293        }
294    }
295
296    pub fn value_within_range(&self, other: AnyValue) -> bool {
297        use DataType::*;
298        match self {
299            UInt8 => other.extract::<u8>().is_some(),
300            #[cfg(feature = "dtype-u16")]
301            UInt16 => other.extract::<u16>().is_some(),
302            UInt32 => other.extract::<u32>().is_some(),
303            UInt64 => other.extract::<u64>().is_some(),
304            #[cfg(feature = "dtype-u128")]
305            UInt128 => other.extract::<u128>().is_some(),
306            #[cfg(feature = "dtype-i8")]
307            Int8 => other.extract::<i8>().is_some(),
308            #[cfg(feature = "dtype-i16")]
309            Int16 => other.extract::<i16>().is_some(),
310            Int32 => other.extract::<i32>().is_some(),
311            Int64 => other.extract::<i64>().is_some(),
312            #[cfg(feature = "dtype-i128")]
313            Int128 => other.extract::<i128>().is_some(),
314            _ => false,
315        }
316    }
317
318    /// Struct representation of the arrow `month_day_nano_interval` type.
319    #[cfg(feature = "dtype-struct")]
320    pub fn _month_days_ns_struct_type() -> Self {
321        DataType::Struct(vec![
322            Field::new(PlSmallStr::from_static("months"), DataType::Int32),
323            Field::new(PlSmallStr::from_static("days"), DataType::Int32),
324            Field::new(
325                PlSmallStr::from_static("nanoseconds"),
326                DataType::Duration(TimeUnit::Nanoseconds),
327            ),
328        ])
329    }
330
331    /// Check if the whole dtype is known.
332    pub fn is_known(&self) -> bool {
333        match self {
334            DataType::List(inner) => inner.is_known(),
335            #[cfg(feature = "dtype-array")]
336            DataType::Array(inner, _) => inner.is_known(),
337            #[cfg(feature = "dtype-struct")]
338            DataType::Struct(fields) => fields.iter().all(|fld| fld.dtype.is_known()),
339            #[cfg(feature = "dtype-map")]
340            DataType::Map(key, value) => key.is_known() && value.is_known(),
341            DataType::Unknown(_) => false,
342            _ => true,
343        }
344    }
345
346    /// Materialize this datatype if it is unknown. All other datatypes
347    /// are left unchanged.
348    pub fn materialize_unknown(self, allow_unknown: bool) -> PolarsResult<DataType> {
349        match self {
350            DataType::Unknown(u) => match u.materialize() {
351                Some(known) => Ok(known),
352                None => {
353                    if allow_unknown {
354                        Ok(DataType::Unknown(u))
355                    } else {
356                        polars_bail!(SchemaMismatch: "failed to materialize unknown type")
357                    }
358                },
359            },
360            DataType::List(inner) => Ok(DataType::List(Box::new(
361                inner.materialize_unknown(allow_unknown)?,
362            ))),
363            #[cfg(feature = "dtype-array")]
364            DataType::Array(inner, size) => Ok(DataType::Array(
365                Box::new(inner.materialize_unknown(allow_unknown)?),
366                size,
367            )),
368            #[cfg(feature = "dtype-struct")]
369            DataType::Struct(fields) => Ok(DataType::Struct(
370                fields
371                    .into_iter()
372                    .map(|f| {
373                        PolarsResult::Ok(Field::new(
374                            f.name,
375                            f.dtype.materialize_unknown(allow_unknown)?,
376                        ))
377                    })
378                    .try_collect_vec()?,
379            )),
380            #[cfg(feature = "dtype-map")]
381            DataType::Map(key, value) => Ok(DataType::Map(
382                Box::new(key.materialize_unknown(allow_unknown)?),
383                Box::new(value.materialize_unknown(allow_unknown)?),
384            )),
385            _ => Ok(self),
386        }
387    }
388
389    #[cfg(feature = "dtype-array")]
390    /// Get the full shape of a multidimensional array.
391    pub fn get_shape(&self) -> Option<Vec<usize>> {
392        fn get_shape_impl(dt: &DataType, shape: &mut Vec<usize>) {
393            if let DataType::Array(inner, size) = dt {
394                shape.push(*size);
395                get_shape_impl(inner, shape);
396            }
397        }
398
399        if let DataType::Array(inner, size) = self {
400            let mut shape = vec![*size];
401            get_shape_impl(inner, &mut shape);
402            Some(shape)
403        } else {
404            None
405        }
406    }
407
408    /// Get the inner data type of a nested type.
409    #[inline]
410    pub fn inner_dtype(&self) -> Option<&DataType> {
411        match self {
412            DataType::List(inner) => Some(inner),
413            #[cfg(feature = "dtype-array")]
414            DataType::Array(inner, _) => Some(inner),
415            _ => None,
416        }
417    }
418
419    /// Get the inner data type of a nested type.
420    pub fn into_inner_dtype(self) -> Option<DataType> {
421        match self {
422            DataType::List(inner) => Some(*inner),
423            #[cfg(feature = "dtype-array")]
424            DataType::Array(inner, _) => Some(*inner),
425            _ => None,
426        }
427    }
428
429    /// Get the inner data type of a nested type.
430    pub fn try_into_inner_dtype(self) -> PolarsResult<DataType> {
431        match self {
432            DataType::List(inner) => Ok(*inner),
433            #[cfg(feature = "dtype-array")]
434            DataType::Array(inner, _) => Ok(*inner),
435            dt => polars_bail!(InvalidOperation: "cannot get inner datatype of `{dt}`"),
436        }
437    }
438
439    /// Get the absolute inner data type of a nested type.
440    pub fn leaf_dtype(&self) -> &DataType {
441        let mut prev = self;
442        while let Some(dtype) = prev.inner_dtype() {
443            prev = dtype
444        }
445        prev
446    }
447
448    #[cfg(feature = "dtype-array")]
449    /// Get the inner data type of a multidimensional array.
450    pub fn array_leaf_dtype(&self) -> Option<&DataType> {
451        let mut prev = self;
452        match prev {
453            DataType::Array(_, _) => {
454                while let DataType::Array(inner, _) = &prev {
455                    prev = inner;
456                }
457                Some(prev)
458            },
459            _ => None,
460        }
461    }
462
463    /// Cast the leaf types of Lists/Arrays and keep the nesting.
464    pub fn cast_leaf(&self, to: DataType) -> DataType {
465        use DataType::*;
466        match self {
467            List(inner) => List(Box::new(inner.cast_leaf(to))),
468            #[cfg(feature = "dtype-array")]
469            Array(inner, size) => Array(Box::new(inner.cast_leaf(to)), *size),
470            _ => to,
471        }
472    }
473
474    /// Map all leaf types of nested dtypes (list, array, struct) using the
475    /// supplied function.
476    pub fn map_leaves<F: FnMut(DataType) -> DataType>(self, f: &mut F) -> DataType {
477        use DataType::*;
478        match self {
479            List(inner) => List(Box::new(inner.map_leaves(f))),
480            #[cfg(feature = "dtype-array")]
481            Array(inner, size) => Array(Box::new(inner.map_leaves(f)), size),
482            #[cfg(feature = "dtype-struct")]
483            Struct(fields) => {
484                let new_fields = fields
485                    .into_iter()
486                    .map(|fld| Field::new(fld.name, fld.dtype.map_leaves(f)))
487                    .collect();
488                Struct(new_fields)
489            },
490            #[cfg(feature = "dtype-map")]
491            Map(key, value) => Map(Box::new(key.map_leaves(f)), Box::new(value.map_leaves(f))),
492            #[cfg(feature = "dtype-extension")]
493            Extension(ext, storage) => Extension(ext, Box::new(storage.map_leaves(f))),
494            _ => f(self),
495        }
496    }
497
498    /// Return whether the cast to `to` makes sense.
499    ///
500    /// If it `None`, we are not sure.
501    pub fn can_cast_to(&self, to: &DataType) -> Option<bool> {
502        if self == to {
503            return Some(true);
504        }
505        if self.is_primitive_numeric() && to.is_primitive_numeric() {
506            return Some(true);
507        }
508
509        if self.is_null() {
510            return Some(true);
511        }
512
513        use DataType as D;
514        Some(match (self, to) {
515            #[cfg(feature = "dtype-categorical")]
516            (D::Categorical(_, _) | D::Enum(_, _), D::Binary)
517            | (D::Binary, D::Categorical(_, _) | D::Enum(_, _)) => false, // TODO @ cat-rework: why can we not cast to Binary?
518
519            #[cfg(feature = "dtype-categorical")]
520            (D::Categorical(_, _) | D::Enum(_, _), D::String)
521            | (D::String, D::Categorical(_, _) | D::Enum(_, _)) => true,
522
523            #[cfg(feature = "object")]
524            (D::Object(_), D::Object(_)) => true,
525            #[cfg(feature = "object")]
526            (D::Object(_), _) | (_, D::Object(_)) => false,
527
528            (D::Boolean, dt) | (dt, D::Boolean) => match dt {
529                dt if dt.is_primitive_numeric() => true,
530                #[cfg(feature = "dtype-decimal")]
531                D::Decimal(_, _) => true,
532                D::String | D::Binary => true,
533                _ => false,
534            },
535
536            (D::List(from), D::List(to)) => from.can_cast_to(to)?,
537            #[cfg(feature = "dtype-map")]
538            (D::Map(from_key, from_value), D::Map(to_key, to_value)) => {
539                // Same key rule as `MapChunked::cast_with_options`.
540                from_key.matches_schema_type(to_key).is_ok() && from_value.can_cast_to(to_value)?
541            },
542            #[cfg(feature = "dtype-map")]
543            (from @ D::Map(_, _), D::List(to)) => {
544                from.map_entries_dtype().unwrap().can_cast_to(to)?
545            },
546            #[cfg(feature = "dtype-map")]
547            (D::List(from), to @ D::Map(_, _)) => {
548                from.can_cast_to(&to.map_entries_dtype().unwrap())?
549            },
550            #[cfg(feature = "dtype-array")]
551            (D::Array(from, l_width), D::Array(to, r_width)) => {
552                l_width == r_width && from.can_cast_to(to)?
553            },
554            #[cfg(feature = "dtype-struct")]
555            (D::Struct(l_fields), D::Struct(r_fields)) => {
556                if l_fields.is_empty() {
557                    return Some(true);
558                }
559
560                if l_fields.len() != r_fields.len() {
561                    return Some(false);
562                }
563
564                for (l, r) in l_fields.iter().zip(r_fields) {
565                    if !l.dtype().can_cast_to(r.dtype())? {
566                        return Some(false);
567                    }
568                }
569
570                true
571            },
572
573            // @NOTE: we are being conservative
574            _ => return None,
575        })
576    }
577
578    pub fn implode(self) -> DataType {
579        DataType::List(Box::new(self))
580    }
581
582    /// Convert to the physical data type
583    #[must_use]
584    pub fn to_physical(&self) -> DataType {
585        use DataType::*;
586        match self {
587            Date => Int32,
588            Datetime(_, _) => Int64,
589            Duration(_) => Int64,
590            Time => Int64,
591            #[cfg(feature = "dtype-decimal")]
592            Decimal(_, _) => Int128,
593            #[cfg(feature = "dtype-categorical")]
594            Categorical(cats, _) => cats.physical().dtype(),
595            #[cfg(feature = "dtype-categorical")]
596            Enum(fcats, _) => fcats.physical().dtype(),
597            #[cfg(feature = "dtype-array")]
598            Array(dt, width) => Array(Box::new(dt.to_physical()), *width),
599            List(dt) => List(Box::new(dt.to_physical())),
600            #[cfg(feature = "dtype-struct")]
601            Struct(fields) => {
602                let new_fields = fields
603                    .iter()
604                    .map(|s| Field::new(s.name().clone(), s.dtype().to_physical()))
605                    .collect();
606                Struct(new_fields)
607            },
608            #[cfg(feature = "dtype-map")]
609            Map(_, _) => self.map_storage_dtype().unwrap().to_physical(),
610            #[cfg(feature = "dtype-extension")]
611            Extension(_, storage) => storage.to_physical(),
612            _ => self.clone(),
613        }
614    }
615
616    /// Bytes one value of this type takes, or `None` when that depends on the
617    /// value.
618    #[must_use]
619    pub fn byte_width(&self) -> Option<f64> {
620        use DataType::*;
621        Some(match self {
622            Null => 0.0,
623            Boolean => 1.0 / 8.0,
624            Int8 | UInt8 => 1.0,
625            Int16 | UInt16 | Float16 => 2.0,
626            Int32 | UInt32 | Float32 | Date => 4.0,
627            Int64 | UInt64 | Float64 | Datetime(_, _) | Duration(_) | Time => 8.0,
628            Int128 | UInt128 => 16.0,
629            #[cfg(feature = "dtype-decimal")]
630            Decimal(_, _) => 16.0,
631            #[cfg(feature = "dtype-categorical")]
632            Categorical(cats, _) => cats.physical().dtype().byte_width()?,
633            #[cfg(feature = "dtype-categorical")]
634            Enum(fcats, _) => fcats.physical().dtype().byte_width()?,
635            #[cfg(feature = "dtype-array")]
636            Array(inner, width) => inner.byte_width()? * (*width as f64),
637            #[cfg(feature = "dtype-struct")]
638            Struct(fields) => fields
639                .iter()
640                .map(|f| f.dtype().byte_width())
641                .sum::<Option<f64>>()?,
642            #[cfg(feature = "dtype-extension")]
643            Extension(_, storage) => storage.byte_width()?,
644            _ => return None,
645        })
646    }
647
648    #[must_use]
649    pub fn to_storage(&self) -> DataType {
650        use DataType::*;
651        match self {
652            #[cfg(feature = "dtype-extension")]
653            Extension(_, storage) => storage.to_storage(),
654            _ => self.clone(),
655        }
656    }
657
658    pub fn is_supported_list_arithmetic_input(&self) -> bool {
659        self.is_primitive_numeric() || self.is_bool() || self.is_null()
660    }
661
662    /// Whether `arr.dot` has a kernel for this inner dtype.
663    pub fn is_supported_array_dot_input(&self) -> bool {
664        use DataType::*;
665        match self {
666            Int8 | Int16 | Int32 | Int64 => true,
667            #[cfg(feature = "dtype-i128")]
668            Int128 => true,
669            UInt8 | UInt16 | UInt32 | UInt64 => true,
670            #[cfg(feature = "dtype-u128")]
671            UInt128 => true,
672            Float32 | Float64 => true,
673            _ => false,
674        }
675    }
676
677    /// Check if this [`DataType`] is a logical type
678    pub fn is_logical(&self) -> bool {
679        self != &self.to_physical()
680    }
681
682    /// Check if this [`DataType`] is a temporal type
683    pub fn is_temporal(&self) -> bool {
684        use DataType::*;
685        matches!(self, Date | Datetime(_, _) | Duration(_) | Time)
686    }
687
688    /// Check if datatype is a primitive type. By that we mean that
689    /// it is not a nested or logical type.
690    pub fn is_primitive(&self) -> bool {
691        self.is_primitive_numeric()
692            | matches!(
693                self,
694                DataType::Boolean | DataType::String | DataType::Binary
695            )
696    }
697
698    /// Check if this [`DataType`] is a primitive numeric type (excludes Decimal).
699    pub fn is_primitive_numeric(&self) -> bool {
700        self.is_float() || self.is_integer()
701    }
702
703    /// Check if this [`DataType`] is a boolean.
704    #[inline]
705    pub fn is_bool(&self) -> bool {
706        matches!(self, DataType::Boolean)
707    }
708
709    /// Check if this [`DataType`] is a list.
710    pub fn is_list(&self) -> bool {
711        matches!(self, DataType::List(_))
712    }
713
714    /// Check if this [`DataType`] is an array.
715    pub fn is_array(&self) -> bool {
716        #[cfg(feature = "dtype-array")]
717        {
718            matches!(self, DataType::Array(_, _))
719        }
720        #[cfg(not(feature = "dtype-array"))]
721        {
722            false
723        }
724    }
725
726    pub fn is_nested(&self) -> bool {
727        match self {
728            DataType::List(_) => true,
729            #[cfg(feature = "dtype-array")]
730            DataType::Array(_, _) => true,
731            #[cfg(feature = "dtype-struct")]
732            DataType::Struct(_) => true,
733            #[cfg(feature = "dtype-map")]
734            DataType::Map(_, _) => true,
735            #[cfg(feature = "dtype-extension")]
736            DataType::Extension(_, storage) => storage.is_nested(),
737            _ => false,
738        }
739    }
740
741    /// Check if this [`DataType`] is a struct
742    pub fn is_struct(&self) -> bool {
743        #[cfg(feature = "dtype-struct")]
744        {
745            matches!(self, DataType::Struct(_))
746        }
747        #[cfg(not(feature = "dtype-struct"))]
748        {
749            false
750        }
751    }
752
753    /// Check if this [`DataType`] is a map
754    pub fn is_map(&self) -> bool {
755        #[cfg(feature = "dtype-map")]
756        {
757            matches!(self, DataType::Map(_, _))
758        }
759        #[cfg(not(feature = "dtype-map"))]
760        {
761            false
762        }
763    }
764
765    pub fn is_binary(&self) -> bool {
766        matches!(self, DataType::Binary)
767    }
768
769    pub fn is_date(&self) -> bool {
770        matches!(self, DataType::Date)
771    }
772    pub fn is_datetime(&self) -> bool {
773        matches!(self, DataType::Datetime(..))
774    }
775
776    pub fn is_duration(&self) -> bool {
777        matches!(self, DataType::Duration(..))
778    }
779
780    pub fn is_object(&self) -> bool {
781        #[cfg(feature = "object")]
782        {
783            matches!(self, DataType::Object(_))
784        }
785        #[cfg(not(feature = "object"))]
786        {
787            false
788        }
789    }
790
791    pub fn is_null(&self) -> bool {
792        matches!(self, DataType::Null)
793    }
794
795    pub fn contains_views(&self) -> bool {
796        use DataType::*;
797        match self {
798            Binary | String => true,
799            List(inner) => inner.contains_views(),
800            #[cfg(feature = "dtype-array")]
801            Array(inner, _) => inner.contains_views(),
802            #[cfg(feature = "dtype-struct")]
803            Struct(fields) => fields.iter().any(|field| field.dtype.contains_views()),
804            #[cfg(feature = "dtype-map")]
805            Map(key, value) => key.contains_views() || value.contains_views(),
806            #[cfg(feature = "dtype-extension")]
807            Extension(_, storage) => storage.contains_views(),
808            _ => false,
809        }
810    }
811
812    pub fn contains_categoricals(&self) -> bool {
813        use DataType::*;
814        match self {
815            #[cfg(feature = "dtype-categorical")]
816            Categorical(_, _) => true,
817            List(inner) => inner.contains_categoricals(),
818            #[cfg(feature = "dtype-array")]
819            Array(inner, _) => inner.contains_categoricals(),
820            #[cfg(feature = "dtype-struct")]
821            Struct(fields) => fields
822                .iter()
823                .any(|field| field.dtype.contains_categoricals()),
824            #[cfg(feature = "dtype-map")]
825            Map(key, value) => key.contains_categoricals() || value.contains_categoricals(),
826            #[cfg(feature = "dtype-extension")]
827            Extension(_, storage) => storage.contains_categoricals(),
828            _ => false,
829        }
830    }
831
832    pub fn contains_enums(&self) -> bool {
833        use DataType::*;
834        match self {
835            #[cfg(feature = "dtype-categorical")]
836            Enum(_, _) => true,
837            List(inner) => inner.contains_enums(),
838            #[cfg(feature = "dtype-array")]
839            Array(inner, _) => inner.contains_enums(),
840            #[cfg(feature = "dtype-struct")]
841            Struct(fields) => fields.iter().any(|field| field.dtype.contains_enums()),
842            #[cfg(feature = "dtype-map")]
843            Map(key, value) => key.contains_enums() || value.contains_enums(),
844            #[cfg(feature = "dtype-extension")]
845            Extension(_, storage) => storage.contains_enums(),
846            _ => false,
847        }
848    }
849
850    pub fn contains_objects(&self) -> bool {
851        use DataType::*;
852        match self {
853            #[cfg(feature = "object")]
854            Object(_) => true,
855            List(inner) => inner.contains_objects(),
856            #[cfg(feature = "dtype-array")]
857            Array(inner, _) => inner.contains_objects(),
858            #[cfg(feature = "dtype-struct")]
859            Struct(fields) => fields.iter().any(|field| field.dtype.contains_objects()),
860            #[cfg(feature = "dtype-map")]
861            Map(key, value) => key.contains_objects() || value.contains_objects(),
862            #[cfg(feature = "dtype-extension")]
863            Extension(_, storage) => storage.contains_objects(),
864            _ => false,
865        }
866    }
867
868    pub fn contains_map(&self) -> bool {
869        use DataType as D;
870        match self {
871            #[cfg(feature = "dtype-map")]
872            D::Map(_, _) => true,
873            D::List(inner) => inner.contains_map(),
874            #[cfg(feature = "dtype-array")]
875            D::Array(inner, _) => inner.contains_map(),
876            #[cfg(feature = "dtype-struct")]
877            D::Struct(fields) => fields.iter().any(|field| field.dtype.contains_map()),
878            #[cfg(feature = "dtype-extension")]
879            D::Extension(_, storage) => storage.contains_map(),
880            _ => false,
881        }
882    }
883
884    pub fn contains_list_recursive(&self) -> bool {
885        use DataType as D;
886        match self {
887            D::List(_) => true,
888            #[cfg(feature = "dtype-array")]
889            D::Array(inner, _) => inner.contains_list_recursive(),
890            #[cfg(feature = "dtype-struct")]
891            D::Struct(fields) => fields
892                .iter()
893                .any(|field| field.dtype.contains_list_recursive()),
894            // The storage of a Map is a list, so its offsets need the same
895            // normalization a `List` needs.
896            #[cfg(feature = "dtype-map")]
897            D::Map(_, _) => true,
898            #[cfg(feature = "dtype-extension")]
899            D::Extension(_, storage) => storage.contains_list_recursive(),
900            _ => false,
901        }
902    }
903
904    pub fn contains_unknown(&self) -> bool {
905        use DataType as D;
906        match self {
907            D::Unknown(_) => true,
908            D::List(inner) => inner.contains_unknown(),
909            #[cfg(feature = "dtype-array")]
910            D::Array(inner, _) => inner.contains_unknown(),
911            #[cfg(feature = "dtype-struct")]
912            D::Struct(fields) => fields.iter().any(|field| field.dtype.contains_unknown()),
913            #[cfg(feature = "dtype-map")]
914            D::Map(key, value) => key.contains_unknown() || value.contains_unknown(),
915            #[cfg(feature = "dtype-extension")]
916            D::Extension(_, storage) => storage.contains_unknown(),
917            _ => false,
918        }
919    }
920
921    pub fn contains_dtype_recursive(&self, dtype: &DataType) -> bool {
922        if self == dtype {
923            return true;
924        }
925        use DataType as D;
926        match self {
927            D::List(inner) => inner.contains_dtype_recursive(dtype),
928            #[cfg(feature = "dtype-array")]
929            D::Array(inner, _) => inner.contains_dtype_recursive(dtype),
930            #[cfg(feature = "dtype-struct")]
931            D::Struct(fields) => fields
932                .iter()
933                .any(|field| field.dtype.contains_dtype_recursive(dtype)),
934            #[cfg(feature = "dtype-map")]
935            D::Map(key, value) => {
936                key.contains_dtype_recursive(dtype) || value.contains_dtype_recursive(dtype)
937            },
938            #[cfg(feature = "dtype-extension")]
939            D::Extension(_, storage) => storage.contains_dtype_recursive(dtype),
940            _ => false,
941        }
942    }
943
944    /// Check if type is sortable
945    pub fn is_ord(&self) -> bool {
946        let phys = self.to_physical();
947        phys.is_primitive_numeric()
948            || self.is_decimal()
949            || matches!(
950                phys,
951                DataType::Binary | DataType::String | DataType::Boolean
952            )
953    }
954
955    /// Check if this [`DataType`] is a Decimal type (of any scale/precision).
956    pub fn is_decimal(&self) -> bool {
957        match self {
958            #[cfg(feature = "dtype-decimal")]
959            DataType::Decimal(_, _) => true,
960            _ => false,
961        }
962    }
963
964    /// Check if this [`DataType`] is a basic floating point type (excludes Decimal).
965    /// Note, this also includes `Unknown(UnknownKind::Float)`.
966    #[inline]
967    pub fn is_float(&self) -> bool {
968        matches!(
969            self,
970            DataType::Float16
971                | DataType::Float32
972                | DataType::Float64
973                | DataType::Unknown(UnknownKind::Float)
974        )
975    }
976
977    /// Check if this [`DataType`] is an integer. Note, this also includes `Unknown(UnknownKind::Int)`.
978    #[inline]
979    pub fn is_integer(&self) -> bool {
980        matches!(
981            self,
982            DataType::Int8
983                | DataType::Int16
984                | DataType::Int32
985                | DataType::Int64
986                | DataType::Int128
987                | DataType::UInt8
988                | DataType::UInt16
989                | DataType::UInt32
990                | DataType::UInt64
991                | DataType::UInt128
992                | DataType::Unknown(UnknownKind::Int(_))
993        )
994    }
995
996    pub fn is_signed_integer(&self) -> bool {
997        // allow because it cannot be replaced when object feature is activated
998        matches!(
999            self,
1000            DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Int128
1001        )
1002    }
1003
1004    pub fn is_unsigned_integer(&self) -> bool {
1005        matches!(
1006            self,
1007            DataType::UInt8
1008                | DataType::UInt16
1009                | DataType::UInt32
1010                | DataType::UInt64
1011                | DataType::UInt128,
1012        )
1013    }
1014
1015    pub fn is_string(&self) -> bool {
1016        matches!(self, DataType::String | DataType::Unknown(UnknownKind::Str))
1017    }
1018
1019    pub fn is_categorical(&self) -> bool {
1020        #[cfg(feature = "dtype-categorical")]
1021        {
1022            matches!(self, DataType::Categorical(_, _))
1023        }
1024        #[cfg(not(feature = "dtype-categorical"))]
1025        {
1026            false
1027        }
1028    }
1029
1030    pub fn is_enum(&self) -> bool {
1031        #[cfg(feature = "dtype-categorical")]
1032        {
1033            matches!(self, DataType::Enum(_, _))
1034        }
1035        #[cfg(not(feature = "dtype-categorical"))]
1036        {
1037            false
1038        }
1039    }
1040
1041    /// Return the key and value dtypes of a `Map`, or `None` for any other dtype.
1042    #[cfg(feature = "dtype-map")]
1043    pub fn as_map(&self) -> Option<(&DataType, &DataType)> {
1044        match self {
1045            DataType::Map(key, value) => Some((key, value)),
1046            _ => None,
1047        }
1048    }
1049
1050    /// The canonical struct dtype of a `Map` entry.
1051    #[cfg(feature = "dtype-map")]
1052    fn map_entries(key: DataType, value: DataType) -> DataType {
1053        DataType::Struct(vec![
1054            Field::new(MAP_KEY_NAME, key),
1055            Field::new(MAP_VALUE_NAME, value),
1056        ])
1057    }
1058
1059    /// The `Struct {key, value}` entries dtype of this `Map`. Returns `None` for any
1060    /// other dtype.
1061    #[cfg(feature = "dtype-map")]
1062    pub fn map_entries_dtype(&self) -> Option<DataType> {
1063        self.as_map()
1064            .map(|(key, value)| DataType::map_entries(key.clone(), value.clone()))
1065    }
1066
1067    /// Returns the dtype of the [`Series`] used internally to store this `Map`:
1068    /// `List(Struct {key, value})`. Returns `None` for any other dtype.
1069    ///
1070    /// This is intentionally separate from [`DataType::to_storage`]. Adding `Map`
1071    /// there would imply also unwrapping it in [`Series::to_storage`]. Python
1072    /// `map_elements` calls the latter, so each map row would reach the UDF as a
1073    /// `List(Struct)` value instead of a `dict`.
1074    #[cfg(feature = "dtype-map")]
1075    pub fn map_storage_dtype(&self) -> Option<DataType> {
1076        self.map_entries_dtype()
1077            .map(|entries| DataType::List(Box::new(entries)))
1078    }
1079
1080    #[cfg(feature = "dtype-map")]
1081    fn map_from_key_value(key: &DataType, value: &DataType) -> PolarsResult<DataType> {
1082        key.ensure_valid_map_key()?;
1083        value.ensure_valid_map_value()?;
1084        Ok(DataType::Map(
1085            Box::new(key.clone()),
1086            Box::new(value.clone()),
1087        ))
1088    }
1089
1090    /// The `Map` dtype whose entries are `self`, or `None` if `self` cannot be Map entries.
1091    ///
1092    /// Positional, should only be called by Arrow/Parquet readers.
1093    #[cfg(feature = "dtype-map")]
1094    pub(crate) fn map_from_positional_entries_dtype(&self) -> Option<DataType> {
1095        let DataType::Struct(fields) = self else {
1096            return None;
1097        };
1098        let [key, value] = fields.as_slice() else {
1099            return None;
1100        };
1101        DataType::map_from_key_value(key.dtype(), value.dtype()).ok()
1102    }
1103
1104    /// The `Map` dtype whose entries are `self`, matching the `key` and `value` fields by name.
1105    #[cfg(feature = "dtype-map")]
1106    pub fn map_from_named_entries_dtype(&self) -> PolarsResult<DataType> {
1107        crate::chunked_array::logical::ensure_map_entries_dtype(self)?;
1108        let DataType::Struct(fields) = self else {
1109            unreachable!("map entries are a struct")
1110        };
1111        let dtype_of = |name: &PlSmallStr| {
1112            fields
1113                .iter()
1114                .find(|f| f.name() == name)
1115                .expect("entry fields checked above")
1116                .dtype()
1117        };
1118
1119        DataType::map_from_key_value(dtype_of(&MAP_KEY_NAME), dtype_of(&MAP_VALUE_NAME))
1120    }
1121
1122    /// Whether this dtype may be used as the key dtype of a `Map`.
1123    #[cfg(feature = "dtype-map")]
1124    pub fn is_valid_map_key(&self) -> bool {
1125        self.ensure_valid_map_key().is_ok()
1126    }
1127
1128    #[cfg(feature = "dtype-map")]
1129    pub fn ensure_valid_map_key(&self) -> PolarsResult<()> {
1130        // A top-level Null cannot supply a non-null key; nested nulls are fine.
1131        polars_ensure!(
1132            !matches!(self, DataType::Null),
1133            InvalidOperation: "`{self}` cannot be used as a Map key dtype"
1134        );
1135        // Neither is supported by the row encoder.
1136        polars_ensure!(
1137            !self.contains_objects(),
1138            InvalidOperation: "`{self}` cannot be used as a Map key dtype: objects cannot be row-encoded"
1139        );
1140        polars_ensure!(
1141            !self.contains_unknown(),
1142            InvalidOperation: "`{self}` cannot be used as a Map key dtype: it is not materialized"
1143        );
1144
1145        Ok(())
1146    }
1147
1148    /// Whether this dtype may be used as the value dtype of a `Map`.
1149    #[cfg(feature = "dtype-map")]
1150    pub fn is_valid_map_value(&self) -> bool {
1151        self.ensure_valid_map_value().is_ok()
1152    }
1153
1154    #[cfg(feature = "dtype-map")]
1155    pub fn ensure_valid_map_value(&self) -> PolarsResult<()> {
1156        // Map values are a `Struct` field, and a struct cannot hold objects.
1157        polars_ensure!(
1158            !self.contains_objects(),
1159            InvalidOperation: "`{self}` cannot be used as a Map value dtype: objects cannot be nested"
1160        );
1161
1162        Ok(())
1163    }
1164
1165    /// Validate the key and value dtypes of a `Map`. Errors for any other dtype.
1166    #[cfg(feature = "dtype-map")]
1167    pub fn ensure_valid_map_dtype(&self) -> PolarsResult<()> {
1168        let DataType::Map(key, value) = self else {
1169            polars_bail!(InvalidOperation: "`{self}` is not a Map dtype");
1170        };
1171        key.ensure_valid_map_key()?;
1172        value.ensure_valid_map_value()
1173    }
1174
1175    /// Validate every `Map` nested in this dtype. Unlike [`Self::ensure_valid_map_dtype`],
1176    /// this accepts dtypes that are not a `Map` themselves.
1177    #[cfg(feature = "dtype-map")]
1178    pub fn ensure_valid_map_dtypes(&self) -> PolarsResult<()> {
1179        // Keep it cheap for non-Map dtypes.
1180        if !self.contains_map() {
1181            return Ok(());
1182        }
1183
1184        self.try_visit_with(|dtype| {
1185            if dtype.is_map() {
1186                dtype.ensure_valid_map_dtype()?;
1187            }
1188            Ok(())
1189        })
1190    }
1191
1192    pub fn is_extension(&self) -> bool {
1193        #[cfg(feature = "dtype-extension")]
1194        {
1195            matches!(self, DataType::Extension(_, _))
1196        }
1197        #[cfg(not(feature = "dtype-extension"))]
1198        {
1199            false
1200        }
1201    }
1202
1203    /// Convert to an Arrow Field.
1204    pub fn to_arrow_field(&self, name: PlSmallStr, compat_level: CompatLevel) -> ArrowField {
1205        let field = ArrowField::new(name, self.to_arrow(compat_level), true);
1206
1207        if let Some(metadata) = self.to_arrow_field_metadata() {
1208            field.with_metadata(metadata)
1209        } else {
1210            field
1211        }
1212    }
1213
1214    pub fn to_arrow_field_metadata(&self) -> Option<Metadata> {
1215        match self {
1216            #[cfg(feature = "dtype-categorical")]
1217            DataType::Enum(fcats, _map) => {
1218                let cats = fcats.categories();
1219                let strings_size: usize = cats
1220                    .values_iter()
1221                    .map(|s| (s.len() + 1).ilog10() as usize + 1 + s.len())
1222                    .sum();
1223                let mut encoded = String::with_capacity(strings_size);
1224                for cat in cats.values_iter() {
1225                    encoded.push_str(itoa::Buffer::new().format(cat.len()));
1226                    encoded.push(';');
1227                    encoded.push_str(cat);
1228                }
1229                Some(BTreeMap::from([(
1230                    PlSmallStr::from_static(DTYPE_ENUM_VALUES_NEW),
1231                    PlSmallStr::from_string(encoded),
1232                )]))
1233            },
1234            #[cfg(feature = "dtype-categorical")]
1235            DataType::Categorical(cats, _) => {
1236                let mut encoded = String::new();
1237                encoded.push_str(itoa::Buffer::new().format(cats.name().len()));
1238                encoded.push(';');
1239                encoded.push_str(cats.name());
1240                encoded.push_str(itoa::Buffer::new().format(cats.namespace().len()));
1241                encoded.push(';');
1242                encoded.push_str(cats.namespace());
1243                encoded.push_str(cats.physical().as_str());
1244                encoded.push(';');
1245
1246                Some(BTreeMap::from([(
1247                    PlSmallStr::from_static(DTYPE_CATEGORICAL_NEW),
1248                    PlSmallStr::from_string(encoded),
1249                )]))
1250            },
1251            DataType::BinaryOffset => Some(BTreeMap::from([(
1252                PlSmallStr::from_static(PL_KEY),
1253                PlSmallStr::from_static(MAINTAIN_PL_TYPE),
1254            )])),
1255            #[cfg(feature = "dtype-extension")]
1256            DataType::Extension(_ext, storage) => storage.to_arrow_field_metadata(),
1257            _ => None,
1258        }
1259    }
1260
1261    /// Try to get the maximum value for this datatype.
1262    pub fn max(&self) -> PolarsResult<Scalar> {
1263        use DataType::*;
1264        let v = match self {
1265            Int8 => Scalar::from(i8::MAX),
1266            Int16 => Scalar::from(i16::MAX),
1267            Int32 => Scalar::from(i32::MAX),
1268            Int64 => Scalar::from(i64::MAX),
1269            Int128 => Scalar::from(i128::MAX),
1270            UInt8 => Scalar::from(u8::MAX),
1271            UInt16 => Scalar::from(u16::MAX),
1272            UInt32 => Scalar::from(u32::MAX),
1273            UInt64 => Scalar::from(u64::MAX),
1274            UInt128 => Scalar::from(u128::MAX),
1275            Float16 => Scalar::from(pf16::INFINITY),
1276            Float32 => Scalar::from(f32::INFINITY),
1277            Float64 => Scalar::from(f64::INFINITY),
1278            #[cfg(feature = "dtype-time")]
1279            Time => Scalar::new(Time, AnyValue::Time(NS_IN_DAY - 1)),
1280            dt => polars_bail!(ComputeError: "cannot determine upper bound for dtype `{dt}`"),
1281        };
1282        Ok(v)
1283    }
1284
1285    /// Try to get the minimum value for this datatype.
1286    pub fn min(&self) -> PolarsResult<Scalar> {
1287        use DataType::*;
1288        let v = match self {
1289            Int8 => Scalar::from(i8::MIN),
1290            Int16 => Scalar::from(i16::MIN),
1291            Int32 => Scalar::from(i32::MIN),
1292            Int64 => Scalar::from(i64::MIN),
1293            Int128 => Scalar::from(i128::MIN),
1294            UInt8 => Scalar::from(u8::MIN),
1295            UInt16 => Scalar::from(u16::MIN),
1296            UInt32 => Scalar::from(u32::MIN),
1297            UInt64 => Scalar::from(u64::MIN),
1298            UInt128 => Scalar::from(u128::MIN),
1299            Float16 => Scalar::from(pf16::NEG_INFINITY),
1300            Float32 => Scalar::from(f32::NEG_INFINITY),
1301            Float64 => Scalar::from(f64::NEG_INFINITY),
1302            #[cfg(feature = "dtype-time")]
1303            Time => Scalar::new(Time, AnyValue::Time(0)),
1304            dt => polars_bail!(ComputeError: "cannot determine lower bound for dtype `{}`", dt),
1305        };
1306        Ok(v)
1307    }
1308
1309    /// Convert to an Arrow data type.
1310    #[inline]
1311    pub fn to_arrow(&self, compat_level: CompatLevel) -> ArrowDataType {
1312        self.try_to_arrow(compat_level).unwrap()
1313    }
1314
1315    #[inline]
1316    pub fn try_to_arrow(&self, compat_level: CompatLevel) -> PolarsResult<ArrowDataType> {
1317        use DataType::*;
1318        match self {
1319            Boolean => Ok(ArrowDataType::Boolean),
1320            UInt8 => Ok(ArrowDataType::UInt8),
1321            UInt16 => Ok(ArrowDataType::UInt16),
1322            UInt32 => Ok(ArrowDataType::UInt32),
1323            UInt64 => Ok(ArrowDataType::UInt64),
1324            UInt128 => Ok(ArrowDataType::UInt128),
1325            Int8 => Ok(ArrowDataType::Int8),
1326            Int16 => Ok(ArrowDataType::Int16),
1327            Int32 => Ok(ArrowDataType::Int32),
1328            Int64 => Ok(ArrowDataType::Int64),
1329            Int128 => Ok(ArrowDataType::Int128),
1330            Float16 => Ok(ArrowDataType::Float16),
1331            Float32 => Ok(ArrowDataType::Float32),
1332            Float64 => Ok(ArrowDataType::Float64),
1333            #[cfg(feature = "dtype-decimal")]
1334            Decimal(precision, scale) => {
1335                assert!(*precision >= 1 && *precision <= 38);
1336                Ok(ArrowDataType::Decimal(*precision, *scale))
1337            },
1338            String => {
1339                let dt = if compat_level.0 >= 1 {
1340                    ArrowDataType::Utf8View
1341                } else {
1342                    ArrowDataType::LargeUtf8
1343                };
1344                Ok(dt)
1345            },
1346            Binary => {
1347                let dt = if compat_level.0 >= 1 {
1348                    ArrowDataType::BinaryView
1349                } else {
1350                    ArrowDataType::LargeBinary
1351                };
1352                Ok(dt)
1353            },
1354            Date => Ok(ArrowDataType::Date32),
1355            Datetime(unit, tz) => Ok(ArrowDataType::Timestamp(
1356                unit.to_arrow(),
1357                tz.as_deref().cloned(),
1358            )),
1359            Duration(unit) => Ok(ArrowDataType::Duration(unit.to_arrow())),
1360            Time => Ok(ArrowDataType::Time64(ArrowTimeUnit::Nanosecond)),
1361            #[cfg(feature = "dtype-array")]
1362            Array(dt, width) => Ok(ArrowDataType::FixedSizeList(
1363                Box::new(dt.to_arrow_field(LIST_VALUES_NAME, compat_level)),
1364                *width,
1365            )),
1366            List(dt) => Ok(ArrowDataType::LargeList(Box::new(
1367                dt.to_arrow_field(LIST_VALUES_NAME, compat_level),
1368            ))),
1369            Null => Ok(ArrowDataType::Null),
1370            #[cfg(feature = "object")]
1371            Object(_) => Ok(get_object_physical_type()),
1372            #[cfg(feature = "dtype-categorical")]
1373            Categorical(_, _) | Enum(_, _) => {
1374                let arrow_phys = match self.cat_physical().unwrap() {
1375                    CategoricalPhysical::U8 => IntegerType::UInt8,
1376                    CategoricalPhysical::U16 => IntegerType::UInt16,
1377                    CategoricalPhysical::U32 => IntegerType::UInt32,
1378                };
1379
1380                let values = if compat_level.0 >= 1 {
1381                    ArrowDataType::Utf8View
1382                } else {
1383                    ArrowDataType::LargeUtf8
1384                };
1385
1386                Ok(ArrowDataType::Dictionary(
1387                    arrow_phys,
1388                    Box::new(values),
1389                    matches!(self, Enum(_, _)),
1390                ))
1391            },
1392            #[cfg(feature = "dtype-struct")]
1393            Struct(fields) => {
1394                let fields = fields
1395                    .iter()
1396                    .map(|fld| fld.to_arrow(compat_level))
1397                    .collect();
1398                Ok(ArrowDataType::Struct(fields))
1399            },
1400            BinaryOffset => Ok(ArrowDataType::LargeBinary),
1401            #[cfg(feature = "dtype-map")]
1402            Map(_, _) => {
1403                let entries = self.map_entries_dtype().unwrap();
1404                let mut field = entries.to_arrow_field(MAP_ENTRIES_NAME, compat_level);
1405                // Neither the entries field nor the key field may be nullable.
1406                field.is_nullable = false;
1407                if let ArrowDataType::Struct(fields) = &mut field.dtype {
1408                    fields[0].is_nullable = false;
1409                }
1410                Ok(ArrowDataType::Map(Box::new(field), false))
1411            },
1412            #[cfg(feature = "dtype-extension")]
1413            Extension(typ, inner) => Ok(ArrowDataType::Extension(Box::new(
1414                polars_arrow::datatypes::ExtensionType {
1415                    name: typ.name().into(),
1416                    inner: inner.try_to_arrow(compat_level)?,
1417                    metadata: typ.serialize_metadata().map(|m| m.into()),
1418                },
1419            ))),
1420            Unknown(kind) => {
1421                let dt = match kind {
1422                    UnknownKind::Any => ArrowDataType::Unknown,
1423                    UnknownKind::Float => ArrowDataType::Float64,
1424                    UnknownKind::Str => ArrowDataType::Utf8View,
1425                    UnknownKind::Int(v) => {
1426                        return materialize_dyn_int(*v).dtype().try_to_arrow(compat_level);
1427                    },
1428                };
1429                Ok(dt)
1430            },
1431        }
1432    }
1433
1434    pub fn is_nested_null(&self) -> bool {
1435        use DataType::*;
1436        match self {
1437            Null => true,
1438            List(field) => field.is_nested_null(),
1439            #[cfg(feature = "dtype-array")]
1440            Array(field, _) => field.is_nested_null(),
1441            #[cfg(feature = "dtype-struct")]
1442            Struct(fields) => fields.iter().all(|fld| fld.dtype.is_nested_null()),
1443            #[cfg(feature = "dtype-map")]
1444            Map(key, value) => key.is_nested_null() && value.is_nested_null(),
1445            #[cfg(feature = "dtype-extension")]
1446            Extension(_, storage) => storage.is_nested_null(),
1447            _ => false,
1448        }
1449    }
1450
1451    /// Answers if this type matches the given type of a schema.
1452    ///
1453    /// Allows (nested) Null types in this type to match any type in the schema,
1454    /// but not vice versa. In such a case Ok(true) is returned, because a cast
1455    /// is necessary. If no cast is necessary Ok(false) is returned, and an
1456    /// error is returned if the types, container shapes, or Struct field names
1457    /// are incompatible.
1458    pub fn matches_schema_type(&self, schema_type: &DataType) -> PolarsResult<bool> {
1459        match (self, schema_type) {
1460            (DataType::List(l), DataType::List(r)) => l.matches_schema_type(r),
1461            #[cfg(feature = "dtype-array")]
1462            (DataType::Array(l, sl), DataType::Array(r, sr)) => {
1463                polars_ensure!(
1464                    sl == sr,
1465                    SchemaMismatch: "array widths differ: {sl} vs {sr}"
1466                );
1467                l.matches_schema_type(r)
1468            },
1469            #[cfg(feature = "dtype-struct")]
1470            (DataType::Struct(l), DataType::Struct(r)) => {
1471                if l.len() != r.len() {
1472                    polars_bail!(SchemaMismatch: "structs have different number of fields: {} vs {}", l.len(), r.len());
1473                }
1474                let mut must_cast = false;
1475                for (l, r) in l.iter().zip(r.iter()) {
1476                    polars_ensure!(
1477                        l.name() == r.name(),
1478                        SchemaMismatch: "struct field names differ: `{}` vs `{}`",
1479                        l.name(), r.name(),
1480                    );
1481                    must_cast |= l.dtype.matches_schema_type(&r.dtype)?;
1482                }
1483                Ok(must_cast)
1484            },
1485            #[cfg(feature = "dtype-map")]
1486            (DataType::Map(lk, lv), DataType::Map(rk, rv)) => {
1487                let key_cast = lk.matches_schema_type(rk)?;
1488                let value_cast = lv.matches_schema_type(rv)?;
1489                Ok(key_cast || value_cast)
1490            },
1491            (DataType::Null, DataType::Null) => Ok(false),
1492            #[cfg(feature = "dtype-decimal")]
1493            (DataType::Decimal(p1, s1), DataType::Decimal(p2, s2)) => Ok((p1, s1) != (p2, s2)),
1494            // We don't allow the other way around, only if our current type is
1495            // null and the schema isn't we allow it.
1496            (DataType::Null, _) => Ok(true),
1497            #[cfg(feature = "dtype-categorical")]
1498            (DataType::Categorical(l, _), DataType::Categorical(r, _)) => {
1499                ensure_same_categories(l, r)?;
1500                Ok(false)
1501            },
1502            #[cfg(feature = "dtype-categorical")]
1503            (DataType::Enum(l, _), DataType::Enum(r, _)) => {
1504                ensure_same_frozen_categories(l, r)?;
1505                Ok(false)
1506            },
1507
1508            (l, r) if l == r => Ok(false),
1509            (l, r) => {
1510                polars_bail!(SchemaMismatch: "type {:?} is incompatible with expected type {:?}", l, r)
1511            },
1512        }
1513    }
1514
1515    #[inline]
1516    pub fn is_unknown(&self) -> bool {
1517        matches!(self, DataType::Unknown(_))
1518    }
1519
1520    pub fn nesting_level(&self) -> usize {
1521        let mut level = 0;
1522        let mut slf = self;
1523        while let Some(inner_dtype) = slf.inner_dtype() {
1524            level += 1;
1525            slf = inner_dtype;
1526        }
1527        level
1528    }
1529
1530    /// If this dtype is a Categorical or Enum, returns the physical backing type.
1531    #[cfg(feature = "dtype-categorical")]
1532    pub fn cat_physical(&self) -> PolarsResult<CategoricalPhysical> {
1533        match self {
1534            DataType::Categorical(cats, _) => Ok(cats.physical()),
1535            DataType::Enum(fcats, _) => Ok(fcats.physical()),
1536            _ => {
1537                polars_bail!(SchemaMismatch: "invalid dtype: expected an Enum or Categorical type, received '{:?}'", self)
1538            },
1539        }
1540    }
1541
1542    /// If this dtype is a Categorical or Enum, returns the underlying mapping.
1543    #[cfg(feature = "dtype-categorical")]
1544    pub fn cat_mapping(&self) -> PolarsResult<&Arc<CategoricalMapping>> {
1545        match self {
1546            DataType::Categorical(_, mapping) | DataType::Enum(_, mapping) => Ok(mapping),
1547            _ => {
1548                polars_bail!(SchemaMismatch: "invalid dtype: expected an Enum or Categorical type, received '{:?}'", self)
1549            },
1550        }
1551    }
1552
1553    #[cfg(feature = "dtype-categorical")]
1554    pub fn from_categories(cats: Arc<Categories>) -> Self {
1555        let mapping = cats.mapping();
1556        Self::Categorical(cats, mapping)
1557    }
1558
1559    #[cfg(feature = "dtype-categorical")]
1560    pub fn from_frozen_categories(fcats: Arc<FrozenCategories>) -> Self {
1561        let mapping = fcats.mapping().clone();
1562        Self::Enum(fcats, mapping)
1563    }
1564
1565    pub fn is_numeric(&self) -> bool {
1566        self.is_integer() || self.is_float() || self.is_decimal()
1567    }
1568
1569    pub fn numeric_to_unsigned_bit_repr(&self) -> Option<DataType> {
1570        use DataType::*;
1571
1572        Some(match self {
1573            Int8 | UInt8 => UInt8,
1574            Int16 | UInt16 | Float16 => UInt16,
1575            Int32 | UInt32 | Float32 => UInt32,
1576            Int64 | UInt64 | Float64 => UInt64,
1577            Int128 | UInt128 => UInt128,
1578            _ => return None,
1579        })
1580    }
1581}
1582
1583impl Display for DataType {
1584    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1585        let s = match self {
1586            DataType::Null => "null",
1587            DataType::Boolean => "bool",
1588            DataType::UInt8 => "u8",
1589            DataType::UInt16 => "u16",
1590            DataType::UInt32 => "u32",
1591            DataType::UInt64 => "u64",
1592            DataType::UInt128 => "u128",
1593            DataType::Int8 => "i8",
1594            DataType::Int16 => "i16",
1595            DataType::Int32 => "i32",
1596            DataType::Int64 => "i64",
1597            DataType::Int128 => "i128",
1598            DataType::Float16 => "f16",
1599            DataType::Float32 => "f32",
1600            DataType::Float64 => "f64",
1601            #[cfg(feature = "dtype-decimal")]
1602            DataType::Decimal(p, s) => return write!(f, "decimal[{p},{s}]"),
1603            DataType::String => "str",
1604            DataType::Binary => "binary",
1605            DataType::BinaryOffset => "binary[offset]",
1606            DataType::Date => "date",
1607            DataType::Datetime(tu, None) => return write!(f, "datetime[{tu}]"),
1608            DataType::Datetime(tu, Some(tz)) => return write!(f, "datetime[{tu}, {tz}]"),
1609            DataType::Duration(tu) => return write!(f, "duration[{tu}]"),
1610            DataType::Time => "time",
1611            #[cfg(feature = "dtype-array")]
1612            DataType::Array(_, _) => {
1613                let tp = self.array_leaf_dtype().unwrap();
1614
1615                let dims = self.get_shape().unwrap();
1616                let shape = if dims.len() == 1 {
1617                    format!("{}", dims[0])
1618                } else {
1619                    format_tuple!(dims)
1620                };
1621                return write!(f, "array[{tp}, {shape}]");
1622            },
1623            DataType::List(tp) => return write!(f, "list[{tp}]"),
1624            #[cfg(feature = "object")]
1625            DataType::Object(s) => s,
1626            #[cfg(feature = "dtype-categorical")]
1627            DataType::Categorical(_, _) => "cat",
1628            #[cfg(feature = "dtype-categorical")]
1629            DataType::Enum(_, _) => "enum",
1630            #[cfg(feature = "dtype-struct")]
1631            DataType::Struct(fields) => return write!(f, "struct[{}]", fields.len()),
1632            #[cfg(feature = "dtype-map")]
1633            DataType::Map(key, value) => return write!(f, "map[{key}, {value}]"),
1634            #[cfg(feature = "dtype-extension")]
1635            DataType::Extension(typ, _) => return write!(f, "ext[{}]", typ.0.dyn_display()),
1636            DataType::Unknown(kind) => match kind {
1637                UnknownKind::Any => "unknown",
1638                UnknownKind::Int(_) => "dyn int",
1639                UnknownKind::Float => "dyn float",
1640                UnknownKind::Str => "dyn str",
1641            },
1642        };
1643        f.write_str(s)
1644    }
1645}
1646
1647impl std::fmt::Debug for DataType {
1648    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1649        use DataType::*;
1650        match self {
1651            Boolean => write!(f, "Boolean"),
1652            UInt8 => write!(f, "UInt8"),
1653            UInt16 => write!(f, "UInt16"),
1654            UInt32 => write!(f, "UInt32"),
1655            UInt64 => write!(f, "UInt64"),
1656            UInt128 => write!(f, "UInt128"),
1657            Int8 => write!(f, "Int8"),
1658            Int16 => write!(f, "Int16"),
1659            Int32 => write!(f, "Int32"),
1660            Int64 => write!(f, "Int64"),
1661            Int128 => write!(f, "Int128"),
1662            Float16 => write!(f, "Float16"),
1663            Float32 => write!(f, "Float32"),
1664            Float64 => write!(f, "Float64"),
1665            String => write!(f, "String"),
1666            Binary => write!(f, "Binary"),
1667            BinaryOffset => write!(f, "BinaryOffset"),
1668            Date => write!(f, "Date"),
1669            Time => write!(f, "Time"),
1670            Duration(unit) => write!(f, "Duration('{unit}')"),
1671            Datetime(unit, opt_tz) => {
1672                if let Some(tz) = opt_tz {
1673                    write!(f, "Datetime('{unit}', '{tz}')")
1674                } else {
1675                    write!(f, "Datetime('{unit}')")
1676                }
1677            },
1678            #[cfg(feature = "dtype-decimal")]
1679            Decimal(p, s) => write!(f, "Decimal({p}, {s})"),
1680            #[cfg(feature = "dtype-array")]
1681            Array(inner, size) => write!(f, "Array({inner:?}, {size})"),
1682            List(inner) => write!(f, "List({inner:?})"),
1683            #[cfg(feature = "dtype-struct")]
1684            Struct(fields) => {
1685                let mut first = true;
1686                write!(f, "Struct({{")?;
1687                for field in fields {
1688                    if !first {
1689                        write!(f, ", ")?;
1690                    }
1691                    write!(f, "'{}': {:?}", field.name(), field.dtype())?;
1692                    first = false;
1693                }
1694                write!(f, "}})")
1695            },
1696            #[cfg(feature = "dtype-categorical")]
1697            Categorical(cats, _) => {
1698                if cats.is_global() {
1699                    write!(f, "Categorical")
1700                } else if cats.namespace().is_empty() && cats.physical() == CategoricalPhysical::U32
1701                {
1702                    write!(f, "Categorical('{}')", cats.name())
1703                } else {
1704                    write!(
1705                        f,
1706                        "Categorical('{}', '{}', {:?})",
1707                        cats.name(),
1708                        cats.namespace(),
1709                        cats.physical()
1710                    )
1711                }
1712            },
1713            #[cfg(feature = "dtype-categorical")]
1714            Enum(_, _) => write!(f, "Enum([...])"),
1715            #[cfg(feature = "object")]
1716            Object(_) => write!(f, "Object"),
1717            Null => write!(f, "Null"),
1718            #[cfg(feature = "dtype-map")]
1719            Map(key, value) => write!(f, "Map({key:?}, {value:?})"),
1720            #[cfg(feature = "dtype-extension")]
1721            Extension(typ, inner) => write!(f, "Extension({}, {inner:?})", typ.0.dyn_debug()),
1722            Unknown(kind) => write!(f, "Unknown({kind:?})"),
1723        }
1724    }
1725}
1726
1727pub fn merge_dtypes(left: &DataType, right: &DataType) -> PolarsResult<DataType> {
1728    use DataType::*;
1729    Ok(match (left, right) {
1730        #[cfg(feature = "dtype-categorical")]
1731        (Categorical(cats_l, map), Categorical(cats_r, _)) => {
1732            ensure_same_categories(cats_l, cats_r)?;
1733            Categorical(cats_l.clone(), map.clone())
1734        },
1735        #[cfg(feature = "dtype-categorical")]
1736        (Enum(fcats_l, map), Enum(fcats_r, _)) => {
1737            ensure_same_frozen_categories(fcats_l, fcats_r)?;
1738            Enum(fcats_l.clone(), map.clone())
1739        },
1740        (List(inner_l), List(inner_r)) => {
1741            let merged = merge_dtypes(inner_l, inner_r)?;
1742            List(Box::new(merged))
1743        },
1744        #[cfg(feature = "dtype-struct")]
1745        (Struct(inner_l), Struct(inner_r)) => {
1746            polars_ensure!(inner_l.len() == inner_r.len(), ComputeError: "cannot combine structs with differing amounts of fields ({} != {})", inner_l.len(), inner_r.len());
1747            let fields = inner_l.iter().zip(inner_r.iter()).map(|(l, r)| {
1748                polars_ensure!(l.name() == r.name(), ComputeError: "cannot combine structs with different fields ({} != {})", l.name(), r.name());
1749                let merged = merge_dtypes(l.dtype(), r.dtype())?;
1750                Ok(Field::new(l.name().clone(), merged))
1751            }).collect::<PolarsResult<Vec<_>>>()?;
1752            Struct(fields)
1753        },
1754        #[cfg(feature = "dtype-map")]
1755        (Map(key_l, value_l), Map(key_r, value_r)) => {
1756            polars_ensure!(key_l == key_r, ComputeError: "cannot combine maps with different key types ({key_l} != {key_r})");
1757            Map(key_l.clone(), Box::new(merge_dtypes(value_l, value_r)?))
1758        },
1759        #[cfg(feature = "dtype-array")]
1760        (Array(inner_l, width_l), Array(inner_r, width_r)) => {
1761            polars_ensure!(width_l == width_r, ComputeError: "widths of FixedSizeList Series are not equal");
1762            let merged = merge_dtypes(inner_l, inner_r)?;
1763            Array(Box::new(merged), *width_l)
1764        },
1765        (left, right) if left == right => left.clone(),
1766        _ => polars_bail!(ComputeError: "unable to merge datatypes"),
1767    })
1768}
1769
1770fn collect_nested_types(
1771    dtype: &DataType,
1772    result: &mut PlHashSet<DataType>,
1773    include_compound_types: bool,
1774) {
1775    match dtype {
1776        DataType::List(inner) => {
1777            if include_compound_types {
1778                result.insert(dtype.clone());
1779            }
1780            collect_nested_types(inner, result, include_compound_types);
1781        },
1782        #[cfg(feature = "dtype-array")]
1783        DataType::Array(inner, _) => {
1784            if include_compound_types {
1785                result.insert(dtype.clone());
1786            }
1787            collect_nested_types(inner, result, include_compound_types);
1788        },
1789        #[cfg(feature = "dtype-struct")]
1790        DataType::Struct(fields) => {
1791            if include_compound_types {
1792                result.insert(dtype.clone());
1793            }
1794            for field in fields {
1795                collect_nested_types(field.dtype(), result, include_compound_types);
1796            }
1797        },
1798        #[cfg(feature = "dtype-map")]
1799        DataType::Map(key, value) => {
1800            if include_compound_types {
1801                result.insert(dtype.clone());
1802            }
1803            collect_nested_types(key, result, include_compound_types);
1804            collect_nested_types(value, result, include_compound_types);
1805        },
1806        _ => {
1807            result.insert(dtype.clone());
1808        },
1809    }
1810}
1811
1812pub fn unpack_dtypes(dtype: &DataType, include_compound_types: bool) -> PlHashSet<DataType> {
1813    let mut result = PlHashSet::new();
1814    collect_nested_types(dtype, &mut result, include_compound_types);
1815    result
1816}
1817
1818#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1819#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1820#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
1821pub struct CompatLevel(pub(crate) u16);
1822
1823impl CompatLevel {
1824    #[inline]
1825    pub const fn newest() -> CompatLevel {
1826        CompatLevel(1)
1827    }
1828
1829    pub const fn oldest() -> CompatLevel {
1830        CompatLevel(0)
1831    }
1832
1833    // The following methods are only used internally
1834
1835    #[doc(hidden)]
1836    pub fn with_level(level: u16) -> PolarsResult<CompatLevel> {
1837        if level > CompatLevel::newest().0 {
1838            polars_bail!(InvalidOperation: "invalid compat level");
1839        }
1840        Ok(CompatLevel(level))
1841    }
1842
1843    #[doc(hidden)]
1844    pub fn get_level(&self) -> u16 {
1845        self.0
1846    }
1847
1848    /// Whether this compat level uses Utf8View/BinaryView types.
1849    pub fn uses_binview_types(&self) -> bool {
1850        *self != CompatLevel::oldest()
1851    }
1852}
1853
1854impl DataType {
1855    pub fn visit_with(&self, mut visitor_fn: impl FnMut(&DataType)) {
1856        self.try_visit_with(|dtype| {
1857            visitor_fn(dtype);
1858            Ok(())
1859        })
1860        .unwrap();
1861    }
1862
1863    pub fn try_visit_with(
1864        &self,
1865        mut visitor_fn: impl FnMut(&DataType) -> PolarsResult<()>,
1866    ) -> PolarsResult<()> {
1867        DataType::try_mutate_with(Cow::Borrowed(self), |dtype| {
1868            visitor_fn(dtype.as_ref()).map(|_| dtype)
1869        })
1870        .map(|_| ())
1871    }
1872
1873    pub fn try_mutate_with<'d>(
1874        dtype: Cow<'d, DataType>,
1875        mut visitor_fn: impl FnMut(Cow<'d, DataType>) -> PolarsResult<Cow<'d, DataType>>,
1876    ) -> PolarsResult<Cow<'d, DataType>> {
1877        DtypeVisitor {
1878            visitor_fn: &mut visitor_fn,
1879        }
1880        .visit_rec(dtype)
1881    }
1882}
1883
1884struct DtypeVisitor<'d, 'f> {
1885    visitor_fn: &'f mut dyn FnMut(Cow<'d, DataType>) -> PolarsResult<Cow<'d, DataType>>,
1886}
1887
1888impl<'d, 'f> DtypeVisitor<'d, 'f> {
1889    fn visit_rec(&mut self, dtype: Cow<'d, DataType>) -> PolarsResult<Cow<'d, DataType>> {
1890        let dtype = match dtype.as_ref() {
1891            DataType::List(_) => match dtype {
1892                Cow::Owned(DataType::List(mut inner)) => {
1893                    self.visit_ref_mut(inner.as_mut())?;
1894                    Cow::Owned(DataType::List(inner))
1895                },
1896                Cow::Borrowed(DataType::List(inner)) => {
1897                    let ret = self.visit_rec(Cow::Borrowed(inner.as_ref()))?;
1898
1899                    if std::ptr::eq(ret.as_ref(), inner.as_ref()) {
1900                        dtype
1901                    } else {
1902                        Cow::Owned(DataType::List(Box::new(ret.into_owned())))
1903                    }
1904                },
1905                _ => unreachable!(),
1906            },
1907            #[cfg(feature = "dtype-array")]
1908            DataType::Array(..) => match dtype {
1909                Cow::Owned(DataType::Array(mut inner, width)) => {
1910                    self.visit_ref_mut(inner.as_mut())?;
1911                    Cow::Owned(DataType::Array(inner, width))
1912                },
1913                Cow::Borrowed(DataType::Array(inner, width)) => {
1914                    let ret = self.visit_rec(Cow::Borrowed(inner.as_ref()))?;
1915
1916                    if std::ptr::eq(ret.as_ref(), inner.as_ref()) {
1917                        dtype
1918                    } else {
1919                        Cow::Owned(DataType::Array(Box::new(ret.into_owned()), *width))
1920                    }
1921                },
1922                _ => unreachable!(),
1923            },
1924            #[cfg(feature = "dtype-struct")]
1925            DataType::Struct(_) => match dtype {
1926                Cow::Owned(DataType::Struct(mut fields)) => {
1927                    for f in &mut fields {
1928                        self.visit_ref_mut(&mut f.dtype)?;
1929                    }
1930
1931                    Cow::Owned(DataType::Struct(fields))
1932                },
1933                Cow::Borrowed(DataType::Struct(fields)) => {
1934                    let mut new_fields = vec![];
1935
1936                    for (i, f) in fields.iter().enumerate() {
1937                        let ret = self.visit_rec(Cow::Borrowed(f.dtype()))?;
1938
1939                        if std::ptr::eq(ret.as_ref(), f.dtype()) && new_fields.is_empty() {
1940                            continue;
1941                        }
1942
1943                        if new_fields.is_empty() {
1944                            new_fields.reserve_exact(fields.len());
1945                            new_fields.extend(fields.iter().take(i).cloned());
1946                        }
1947
1948                        new_fields.push(Field::new(f.name().clone(), ret.into_owned()));
1949                    }
1950
1951                    if new_fields.is_empty() {
1952                        dtype
1953                    } else {
1954                        assert_eq!(new_fields.len(), fields.len());
1955                        Cow::Owned(DataType::Struct(new_fields))
1956                    }
1957                },
1958                _ => unreachable!(),
1959            },
1960            #[cfg(feature = "dtype-map")]
1961            DataType::Map(..) => match dtype {
1962                Cow::Owned(DataType::Map(mut key, mut value)) => {
1963                    self.visit_ref_mut(key.as_mut())?;
1964                    self.visit_ref_mut(value.as_mut())?;
1965                    Cow::Owned(DataType::Map(key, value))
1966                },
1967                Cow::Borrowed(DataType::Map(key, value)) => {
1968                    let new_key = self.visit_rec(Cow::Borrowed(key.as_ref()))?;
1969                    let new_value = self.visit_rec(Cow::Borrowed(value.as_ref()))?;
1970
1971                    if std::ptr::eq(new_key.as_ref(), key.as_ref())
1972                        && std::ptr::eq(new_value.as_ref(), value.as_ref())
1973                    {
1974                        dtype
1975                    } else {
1976                        Cow::Owned(DataType::Map(
1977                            Box::new(new_key.into_owned()),
1978                            Box::new(new_value.into_owned()),
1979                        ))
1980                    }
1981                },
1982                _ => unreachable!(),
1983            },
1984            #[cfg(feature = "dtype-extension")]
1985            DataType::Extension(..) => match dtype {
1986                Cow::Owned(DataType::Extension(ext, mut storage)) => {
1987                    self.visit_ref_mut(storage.as_mut())?;
1988                    Cow::Owned(DataType::Extension(ext, storage))
1989                },
1990                Cow::Borrowed(DataType::Extension(ext, storage)) => {
1991                    let ret = self.visit_rec(Cow::Borrowed(storage.as_ref()))?;
1992
1993                    if std::ptr::eq(ret.as_ref(), storage.as_ref()) {
1994                        dtype
1995                    } else {
1996                        Cow::Owned(DataType::Extension(ext.clone(), Box::new(ret.into_owned())))
1997                    }
1998                },
1999                _ => unreachable!(),
2000            },
2001            _ => {
2002                debug_assert!(!dtype.is_nested());
2003                dtype
2004            },
2005        };
2006
2007        (self.visitor_fn)(dtype)
2008    }
2009
2010    /// `dtype` will be set to an unspecified value if this returns an error.
2011    fn visit_ref_mut(&mut self, dtype: &mut DataType) -> PolarsResult<()> {
2012        *dtype = self
2013            .visit_rec(Cow::Owned(std::mem::replace(dtype, DataType::Null)))?
2014            .into_owned();
2015
2016        Ok(())
2017    }
2018}
2019
2020#[cfg(feature = "dtype-categorical")]
2021impl From<CategoricalPhysical> for DataType {
2022    fn from(phys: CategoricalPhysical) -> DataType {
2023        match phys {
2024            CategoricalPhysical::U8 => DataType::UInt8,
2025            CategoricalPhysical::U16 => DataType::UInt16,
2026            CategoricalPhysical::U32 => DataType::UInt32,
2027        }
2028    }
2029}
2030
2031#[cfg(test)]
2032mod tests {
2033    use super::*;
2034
2035    #[cfg(feature = "dtype-array")]
2036    #[test]
2037    fn test_unpack_primitive_dtypes() {
2038        let inner_type = DataType::Float64;
2039        let array_type = DataType::Array(Box::new(inner_type), 10);
2040        let list_type = DataType::List(Box::new(array_type));
2041
2042        let result = unpack_dtypes(&list_type, false);
2043
2044        let mut expected = PlHashSet::new();
2045        expected.insert(DataType::Float64);
2046
2047        assert_eq!(result, expected)
2048    }
2049
2050    #[cfg(feature = "dtype-array")]
2051    #[test]
2052    fn test_unpack_compound_dtypes() {
2053        let inner_type = DataType::Float64;
2054        let array_type = DataType::Array(Box::new(inner_type), 10);
2055        let list_type = DataType::List(Box::new(array_type.clone()));
2056
2057        let result = unpack_dtypes(&list_type, true);
2058
2059        let mut expected = PlHashSet::new();
2060        expected.insert(list_type);
2061        expected.insert(array_type);
2062        expected.insert(DataType::Float64);
2063
2064        assert_eq!(result, expected)
2065    }
2066}