Skip to main content

arrow_schema/
datatype.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::str::FromStr;
19use std::sync::Arc;
20
21use crate::{ArrowError, Field, FieldRef, Fields, UnionFields};
22
23/// Datatypes supported by this implementation of Apache Arrow.
24///
25/// The variants of this enum include primitive fixed size types as well as
26/// parametric or nested types. See [`Schema.fbs`] for Arrow's specification.
27///
28/// # Examples
29///
30/// Primitive types
31/// ```
32/// # use arrow_schema::DataType;
33/// // create a new 32-bit signed integer
34/// let data_type = DataType::Int32;
35/// ```
36///
37/// Nested Types
38/// ```
39/// # use arrow_schema::{DataType, Field};
40/// # use std::sync::Arc;
41/// // create a new list of 32-bit signed integers directly
42/// let list_data_type = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
43/// // Create the same list type with constructor
44/// let list_data_type2 = DataType::new_list(DataType::Int32, true);
45/// assert_eq!(list_data_type, list_data_type2);
46/// ```
47///
48/// Dictionary Types
49/// ```
50/// # use arrow_schema::{DataType};
51/// // String Dictionary (key type Int32 and value type Utf8)
52/// let data_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
53/// ```
54///
55/// Timestamp Types
56/// ```
57/// # use arrow_schema::{DataType, TimeUnit};
58/// // timestamp with millisecond precision without timezone specified
59/// let data_type = DataType::Timestamp(TimeUnit::Millisecond, None);
60/// // timestamp with nanosecond precision in UTC timezone
61/// let data_type = DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into()));
62///```
63///
64/// # Display and FromStr
65///
66/// The `Display` and `FromStr` implementations for `DataType` are
67/// human-readable, parseable, and reversible.
68///
69/// ```
70/// # use arrow_schema::DataType;
71/// let data_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
72/// let data_type_string = data_type.to_string();
73/// assert_eq!(data_type_string, "Dictionary(Int32, Utf8)");
74/// // display can be parsed back into the original type
75/// let parsed_data_type: DataType = data_type.to_string().parse().unwrap();
76/// assert_eq!(data_type, parsed_data_type);
77/// ```
78///
79/// # Nested Support
80/// Currently, the Rust implementation supports the following nested types:
81///  - `List<T>`
82///  - `LargeList<T>`
83///  - `FixedSizeList<T>`
84///  - `Struct<T, U, V, ...>`
85///  - `Union<T, U, V, ...>`
86///  - `Map<K, V>`
87///
88/// Nested types can themselves be nested within other arrays.
89/// For more information on these types please see
90/// [the physical memory layout of Apache Arrow]
91///
92/// [`Schema.fbs`]: https://github.com/apache/arrow/blob/main/format/Schema.fbs
93/// [the physical memory layout of Apache Arrow]: https://arrow.apache.org/docs/format/Columnar.html#physical-memory-layout
94#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
95#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
96pub enum DataType {
97    /// Null type
98    Null,
99    /// A boolean datatype representing the values `true` and `false`.
100    Boolean,
101    /// A signed 8-bit integer.
102    Int8,
103    /// A signed 16-bit integer.
104    Int16,
105    /// A signed 32-bit integer.
106    Int32,
107    /// A signed 64-bit integer.
108    Int64,
109    /// An unsigned 8-bit integer.
110    UInt8,
111    /// An unsigned 16-bit integer.
112    UInt16,
113    /// An unsigned 32-bit integer.
114    UInt32,
115    /// An unsigned 64-bit integer.
116    UInt64,
117    /// A 16-bit floating point number.
118    Float16,
119    /// A 32-bit floating point number.
120    Float32,
121    /// A 64-bit floating point number.
122    Float64,
123    /// A timestamp with an optional timezone.
124    ///
125    /// Time is measured as a Unix epoch, counting the seconds from
126    /// 00:00:00.000 on 1 January 1970, excluding leap seconds,
127    /// as a signed 64-bit integer.
128    ///
129    /// The time zone is a string indicating the name of a time zone, one of:
130    ///
131    /// * As used in the Olson time zone database (the "tz database" or
132    ///   "tzdata"), such as "America/New_York"
133    /// * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30
134    ///
135    /// Timestamps with a non-empty timezone
136    /// ------------------------------------
137    ///
138    /// If a Timestamp column has a non-empty timezone value, its epoch is
139    /// 1970-01-01 00:00:00 (January 1st 1970, midnight) in the *UTC* timezone
140    /// (the Unix epoch), regardless of the Timestamp's own timezone.
141    ///
142    /// Therefore, timestamp values with a non-empty timezone correspond to
143    /// physical points in time together with some additional information about
144    /// how the data was obtained and/or how to display it (the timezone).
145    ///
146    ///   For example, the timestamp value 0 with the timezone string "Europe/Paris"
147    ///   corresponds to "January 1st 1970, 00h00" in the UTC timezone, but the
148    ///   application may prefer to display it as "January 1st 1970, 01h00" in
149    ///   the Europe/Paris timezone (which is the same physical point in time).
150    ///
151    /// One consequence is that timestamp values with a non-empty timezone
152    /// can be compared and ordered directly, since they all share the same
153    /// well-known point of reference (the Unix epoch).
154    ///
155    /// Timestamps with an unset / empty timezone
156    /// -----------------------------------------
157    ///
158    /// If a Timestamp column has no timezone value, its epoch is
159    /// 1970-01-01 00:00:00 (January 1st 1970, midnight) in an *unknown* timezone.
160    ///
161    /// Therefore, timestamp values without a timezone cannot be meaningfully
162    /// interpreted as physical points in time, but only as calendar / clock
163    /// indications ("wall clock time") in an unspecified timezone.
164    ///
165    ///   For example, the timestamp value 0 with an empty timezone string
166    ///   corresponds to "January 1st 1970, 00h00" in an unknown timezone: there
167    ///   is not enough information to interpret it as a well-defined physical
168    ///   point in time.
169    ///
170    /// One consequence is that timestamp values without a timezone cannot
171    /// be reliably compared or ordered, since they may have different points of
172    /// reference.  In particular, it is *not* possible to interpret an unset
173    /// or empty timezone as the same as "UTC".
174    ///
175    /// Conversion between timezones
176    /// ----------------------------
177    ///
178    /// If a Timestamp column has a non-empty timezone, changing the timezone
179    /// to a different non-empty value is a metadata-only operation:
180    /// the timestamp values need not change as their point of reference remains
181    /// the same (the Unix epoch).
182    ///
183    /// However, if a Timestamp column has no timezone value, changing it to a
184    /// non-empty value requires to think about the desired semantics.
185    /// One possibility is to assume that the original timestamp values are
186    /// relative to the epoch of the timezone being set; timestamp values should
187    /// then adjusted to the Unix epoch (for example, changing the timezone from
188    /// empty to "Europe/Paris" would require converting the timestamp values
189    /// from "Europe/Paris" to "UTC", which seems counter-intuitive but is
190    /// nevertheless correct).
191    ///
192    /// ```
193    /// # use arrow_schema::{DataType, TimeUnit};
194    /// DataType::Timestamp(TimeUnit::Second, None);
195    /// DataType::Timestamp(TimeUnit::Second, Some("literal".into()));
196    /// DataType::Timestamp(TimeUnit::Second, Some("string".to_string().into()));
197    /// ```
198    ///
199    /// # Timezone representation
200    /// ----------------------------
201    /// It is possible to use either the timezone string representation, such as "UTC", or the absolute time zone offset "+00:00".
202    /// For timezones with fixed offsets, such as "UTC" or "JST", the offset representation is recommended, as it is more explicit and less ambiguous.
203    ///
204    /// Most arrow-rs functionalities use the absolute offset representation,
205    /// such as [`PrimitiveArray::with_timezone_utc`] that applies a
206    /// UTC timezone to timestamp arrays.
207    ///
208    /// [`PrimitiveArray::with_timezone_utc`]: https://docs.rs/arrow/latest/arrow/array/struct.PrimitiveArray.html#method.with_timezone_utc
209    ///
210    /// Timezone string parsing
211    /// -----------------------
212    /// When feature `chrono-tz` is not enabled, allowed timezone strings are fixed offsets of the form "+09:00", "-09" or "+0930".
213    ///
214    /// When feature `chrono-tz` is enabled, additional strings supported by [chrono_tz](https://docs.rs/chrono-tz/latest/chrono_tz/)
215    /// are also allowed, which include [IANA database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
216    /// timezones.
217    Timestamp(TimeUnit, Option<Arc<str>>),
218    /// A signed 32-bit date representing the elapsed time since UNIX epoch (1970-01-01)
219    /// in days.
220    Date32,
221    /// A signed 64-bit date representing the elapsed time since UNIX epoch (1970-01-01)
222    /// in milliseconds.
223    ///
224    /// # Valid Ranges
225    ///
226    /// According to the Arrow specification ([Schema.fbs]), values of Date64
227    /// are treated as the number of *days*, in milliseconds, since the UNIX
228    /// epoch. Therefore, values of this type  must be evenly divisible by
229    /// `86_400_000`, the number of milliseconds in a standard day.
230    ///
231    /// It is not valid to store milliseconds that do not represent an exact
232    /// day. The reason for this restriction is compatibility with other
233    /// language's native libraries (specifically Java), which historically
234    /// lacked a dedicated date type and only supported timestamps.
235    ///
236    /// # Validation
237    ///
238    /// This library does not validate or enforce that Date64 values are evenly
239    /// divisible by `86_400_000`  for performance and usability reasons. Date64
240    /// values are treated similarly to `Timestamp(TimeUnit::Millisecond,
241    /// None)`: values will be displayed with a time of day if the value does
242    /// not represent an exact day, and arithmetic will be done at the
243    /// millisecond granularity.
244    ///
245    /// # Recommendation
246    ///
247    /// Users should prefer [`Date32`] to cleanly represent the number
248    /// of days, or one of the Timestamp variants to include time as part of the
249    /// representation, depending on their use case.
250    ///
251    /// # Further Reading
252    ///
253    /// For more details, see [#5288](https://github.com/apache/arrow-rs/issues/5288).
254    ///
255    /// [`Date32`]: Self::Date32
256    /// [Schema.fbs]: https://github.com/apache/arrow/blob/main/format/Schema.fbs
257    Date64,
258    /// A signed 32-bit time representing the elapsed time since midnight in the unit of `TimeUnit`.
259    /// Must be either seconds or milliseconds.
260    Time32(TimeUnit),
261    /// A signed 64-bit time representing the elapsed time since midnight in the unit of `TimeUnit`.
262    /// Must be either microseconds or nanoseconds.
263    Time64(TimeUnit),
264    /// Measure of elapsed time in either seconds, milliseconds, microseconds or nanoseconds.
265    Duration(TimeUnit),
266    /// A "calendar" interval which models types that don't necessarily
267    /// have a precise duration without the context of a base timestamp (e.g.
268    /// days can differ in length during day light savings time transitions).
269    Interval(IntervalUnit),
270    /// Opaque binary data of variable length.
271    ///
272    /// A single Binary array can store up to [`i32::MAX`] bytes
273    /// of binary data in total.
274    Binary,
275    /// Opaque binary data of fixed size.
276    ///
277    /// Enum parameter specifies the number of bytes per value, defined by the
278    /// [`byteWidth` field] in the Arrow Spec
279    ///
280    /// [`byteWidth` field]: https://github.com/apache/arrow/blob/2a89d03bbefd620b42126b8e00f8ae57e99cd638/format/Schema.fbs#L211
281    FixedSizeBinary(i32),
282    /// Opaque binary data of variable length and 64-bit offsets.
283    ///
284    /// A single LargeBinary array can store up to [`i64::MAX`] bytes
285    /// of binary data in total.
286    LargeBinary,
287    /// Opaque binary data of variable length.
288    ///
289    /// Logically the same as [`Binary`], but the internal representation uses a view
290    /// struct that contains the string length and either the string's entire data
291    /// inline (for small strings) or an inlined prefix, an index of another buffer,
292    /// and an offset pointing to a slice in that buffer (for non-small strings).
293    ///
294    /// [`Binary`]: Self::Binary
295    BinaryView,
296    /// A variable-length string in Unicode with UTF-8 encoding.
297    ///
298    /// A single Utf8 array can store up to [`i32::MAX`] bytes
299    /// of string data in total.
300    Utf8,
301    /// A variable-length string in Unicode with UFT-8 encoding and 64-bit offsets.
302    ///
303    /// A single LargeUtf8 array can store up to [`i64::MAX`] bytes
304    /// of string data in total.
305    LargeUtf8,
306    /// A variable-length string in Unicode with UTF-8 encoding
307    ///
308    /// Logically the same as [`Utf8`], but the internal representation uses a view
309    /// struct that contains the string length and either the string's entire data
310    /// inline (for small strings) or an inlined prefix, an index of another buffer,
311    /// and an offset pointing to a slice in that buffer (for non-small strings).
312    ///
313    /// [`Utf8`]: Self::Utf8
314    Utf8View,
315    /// A list of some logical data type with variable length.
316    ///
317    /// A single List array can store up to [`i32::MAX`] elements in total.
318    List(FieldRef),
319    /// A list of some logical data type with variable length.
320    ///
321    /// Logically the same as [`List`], but the internal representation differs in how child
322    /// data is referenced, allowing flexibility in how data is layed out.
323    ///
324    /// [`List`]: Self::List
325    ListView(FieldRef),
326    /// A list of some logical data type with fixed length.
327    FixedSizeList(FieldRef, i32),
328    /// A list of some logical data type with variable length and 64-bit offsets.
329    ///
330    /// A single LargeList array can store up to [`i64::MAX`] elements in total.
331    LargeList(FieldRef),
332    /// A list of some logical data type with variable length and 64-bit offsets.
333    ///
334    /// Logically the same as [`LargeList`], but the internal representation differs in how child
335    /// data is referenced, allowing flexibility in how data is layed out.
336    ///
337    /// [`LargeList`]: Self::LargeList
338    LargeListView(FieldRef),
339    /// A nested datatype that contains a number of sub-fields.
340    Struct(Fields),
341    /// A nested datatype that can represent slots of differing types. Components:
342    ///
343    /// 1. [`UnionFields`]
344    /// 2. The type of union (Sparse or Dense)
345    Union(UnionFields, UnionMode),
346    /// A dictionary encoded array (`key_type`, `value_type`), where
347    /// each array element is an index of `key_type` into an
348    /// associated dictionary of `value_type`.
349    ///
350    /// Dictionary arrays are used to store columns of `value_type`
351    /// that contain many repeated values using less memory, but with
352    /// a higher CPU overhead for some operations.
353    ///
354    /// This type mostly used to represent low cardinality string
355    /// arrays or a limited set of primitive types as integers.
356    Dictionary(Box<DataType>, Box<DataType>),
357    /// Exact 32-bit width decimal value with precision and scale
358    ///
359    /// * precision is the maximum number of digits in the unscaled value
360    /// * scale controls the position of the decimal point
361    ///
362    /// The represented value is the unscaled integer multiplied by 10^{-scale}.
363    /// For example, the unscaled value 12345 with precision 5 and scale 2
364    /// represents 123.45.
365    ///
366    /// Scale can also be negative. For example, the unscaled value 12 with
367    /// precision 2 and scale -3 represents 12000.
368    Decimal32(u8, i8),
369    /// Exact 64-bit width decimal value with precision and scale
370    ///
371    /// * precision is the maximum number of digits in the unscaled value
372    /// * scale controls the position of the decimal point
373    ///
374    /// The represented value is the unscaled integer multiplied by 10^{-scale}.
375    /// For example, the unscaled value 12345 with precision 5 and scale 2
376    /// represents 123.45.
377    ///
378    /// Scale can also be negative. For example, the unscaled value 12 with
379    /// precision 2 and scale -3 represents 12000.
380    Decimal64(u8, i8),
381    /// Exact 128-bit width decimal value with precision and scale
382    ///
383    /// * precision is the maximum number of digits in the unscaled value
384    /// * scale controls the position of the decimal point
385    ///
386    /// The represented value is the unscaled integer multiplied by 10^{-scale}.
387    /// For example, the unscaled value 12345 with precision 5 and scale 2
388    /// represents 123.45.
389    ///
390    /// Scale can also be negative. For example, the unscaled value 12 with
391    /// precision 2 and scale -3 represents 12000.
392    Decimal128(u8, i8),
393    /// Exact 256-bit width decimal value with precision and scale
394    ///
395    /// * precision is the maximum number of digits in the unscaled value
396    /// * scale controls the position of the decimal point
397    ///
398    /// The represented value is the unscaled integer multiplied by 10^{-scale}.
399    /// For example, the unscaled value 12345 with precision 5 and scale 2
400    /// represents 123.45.
401    ///
402    /// Scale can also be negative. For example, the unscaled value 12 with
403    /// precision 2 and scale -3 represents 12000.
404    Decimal256(u8, i8),
405    /// A Map is a logical nested type that is represented as
406    ///
407    /// `List<entries: Struct<key: K, value: V>>`
408    ///
409    /// The keys and values are each respectively contiguous.
410    /// The key and value types are not constrained, but keys should be
411    /// hashable and unique.
412    /// Whether the keys are sorted can be set in the `bool` after the `Field`.
413    ///
414    /// In a field with Map type, the field has a child Struct field, which then
415    /// has two children: key type and the second the value type. The names of the
416    /// child fields may be respectively "entries", "key", and "value", but this is
417    /// not enforced.
418    Map(FieldRef, bool),
419    /// A run-end encoding (REE) is a variation of run-length encoding (RLE). These
420    /// encodings are well-suited for representing data containing sequences of the
421    /// same value, called runs. Each run is represented as a value and an integer giving
422    /// the index in the array where the run ends.
423    ///
424    /// A run-end encoded array has no buffers by itself, but has two child arrays. The
425    /// first child array, called the run ends array, holds either 16, 32, or 64-bit
426    /// signed integers. The actual values of each run are held in the second child array.
427    ///
428    /// These child arrays are prescribed the standard names of "run_ends" and "values"
429    /// respectively.
430    RunEndEncoded(FieldRef, FieldRef),
431}
432
433/// An absolute length of time in seconds, milliseconds, microseconds or nanoseconds.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
435#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
436pub enum TimeUnit {
437    /// Time in seconds.
438    Second,
439    /// Time in milliseconds.
440    Millisecond,
441    /// Time in microseconds.
442    Microsecond,
443    /// Time in nanoseconds.
444    Nanosecond,
445}
446
447impl std::fmt::Display for TimeUnit {
448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449        match self {
450            TimeUnit::Second => write!(f, "s"),
451            TimeUnit::Millisecond => write!(f, "ms"),
452            TimeUnit::Microsecond => write!(f, "µs"),
453            TimeUnit::Nanosecond => write!(f, "ns"),
454        }
455    }
456}
457
458/// YEAR_MONTH, DAY_TIME, MONTH_DAY_NANO interval in SQL style.
459#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
460#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
461pub enum IntervalUnit {
462    /// Indicates the number of elapsed whole months, stored as 4-byte integers.
463    YearMonth,
464    /// Indicates the number of elapsed days and milliseconds,
465    /// stored as 2 contiguous 32-bit integers (days, milliseconds) (8-bytes in total).
466    DayTime,
467    /// A triple of the number of elapsed months, days, and nanoseconds.
468    /// The values are stored contiguously in 16 byte blocks. Months and
469    /// days are encoded as 32 bit integers and nanoseconds is encoded as a
470    /// 64 bit integer. All integers are signed. Each field is independent
471    /// (e.g. there is no constraint that nanoseconds have the same sign
472    /// as days or that the quantity of nanoseconds represents less
473    /// than a day's worth of time).
474    MonthDayNano,
475}
476
477/// Sparse or Dense union layouts
478#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Copy)]
479#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
480pub enum UnionMode {
481    /// Sparse union layout
482    Sparse,
483    /// Dense union layout
484    Dense,
485}
486
487/// Parses `str` into a `DataType`.
488///
489/// This is the reverse of [`DataType`]'s `Display`
490/// impl, and maintains the invariant that
491/// `DataType::try_from(&data_type.to_string()).unwrap() == data_type`
492///
493/// # Example
494/// ```
495/// use arrow_schema::DataType;
496///
497/// let data_type: DataType = "Int32".parse().unwrap();
498/// assert_eq!(data_type, DataType::Int32);
499/// ```
500impl FromStr for DataType {
501    type Err = ArrowError;
502
503    fn from_str(s: &str) -> Result<Self, Self::Err> {
504        crate::datatype_parse::parse_data_type(s)
505    }
506}
507
508impl TryFrom<&str> for DataType {
509    type Error = ArrowError;
510
511    fn try_from(value: &str) -> Result<Self, Self::Error> {
512        value.parse()
513    }
514}
515
516impl DataType {
517    /// Returns true if the type is primitive: (numeric, temporal).
518    #[inline]
519    pub fn is_primitive(&self) -> bool {
520        self.is_numeric() || self.is_temporal()
521    }
522
523    /// Returns true if this type is numeric: (UInt*, Int*, Float*, Decimal*).
524    #[inline]
525    pub fn is_numeric(&self) -> bool {
526        use DataType::*;
527        matches!(
528            self,
529            UInt8
530                | UInt16
531                | UInt32
532                | UInt64
533                | Int8
534                | Int16
535                | Int32
536                | Int64
537                | Float16
538                | Float32
539                | Float64
540                | Decimal32(_, _)
541                | Decimal64(_, _)
542                | Decimal128(_, _)
543                | Decimal256(_, _)
544        )
545    }
546
547    /// Returns true if this type is temporal: (Date*, Time*, Duration, or Interval).
548    #[inline]
549    pub fn is_temporal(&self) -> bool {
550        use DataType::*;
551        matches!(
552            self,
553            Date32 | Date64 | Timestamp(_, _) | Time32(_) | Time64(_) | Duration(_) | Interval(_)
554        )
555    }
556
557    /// Returns true if this type is floating: (Float*).
558    #[inline]
559    pub fn is_floating(&self) -> bool {
560        use DataType::*;
561        matches!(self, Float16 | Float32 | Float64)
562    }
563
564    /// Returns true if this type is integer: (Int*, UInt*).
565    #[inline]
566    pub fn is_integer(&self) -> bool {
567        self.is_signed_integer() || self.is_unsigned_integer()
568    }
569
570    /// Returns true if this type is signed integer: (Int*).
571    #[inline]
572    pub fn is_signed_integer(&self) -> bool {
573        use DataType::*;
574        matches!(self, Int8 | Int16 | Int32 | Int64)
575    }
576
577    /// Returns true if this type is unsigned integer: (UInt*).
578    #[inline]
579    pub fn is_unsigned_integer(&self) -> bool {
580        use DataType::*;
581        matches!(self, UInt8 | UInt16 | UInt32 | UInt64)
582    }
583
584    /// Returns true if this type is decimal: (Decimal*).
585    #[inline]
586    pub fn is_decimal(&self) -> bool {
587        use DataType::*;
588        matches!(
589            self,
590            Decimal32(..) | Decimal64(..) | Decimal128(..) | Decimal256(..)
591        )
592    }
593
594    /// Returns true if this type is valid as a dictionary key
595    #[inline]
596    pub fn is_dictionary_key_type(&self) -> bool {
597        self.is_integer()
598    }
599
600    /// Returns true if this type is valid for run-ends array in RunArray
601    #[inline]
602    pub fn is_run_ends_type(&self) -> bool {
603        use DataType::*;
604        matches!(self, Int16 | Int32 | Int64)
605    }
606
607    /// Returns true if this type is nested (List, FixedSizeList, LargeList, ListView. LargeListView, Struct, Union,
608    /// or Map), or a dictionary of a nested type
609    #[inline]
610    pub fn is_nested(&self) -> bool {
611        use DataType::*;
612        match self {
613            Dictionary(_, v) => DataType::is_nested(v.as_ref()),
614            RunEndEncoded(_, v) => DataType::is_nested(v.data_type()),
615            List(_)
616            | FixedSizeList(_, _)
617            | LargeList(_)
618            | ListView(_)
619            | LargeListView(_)
620            | Struct(_)
621            | Union(_, _)
622            | Map(_, _) => true,
623            _ => false,
624        }
625    }
626
627    /// Returns true if this type is DataType::Null.
628    #[inline]
629    pub fn is_null(&self) -> bool {
630        use DataType::*;
631        matches!(self, Null)
632    }
633
634    /// Returns true if this type is a String type
635    #[inline]
636    pub fn is_string(&self) -> bool {
637        use DataType::*;
638        matches!(self, Utf8 | LargeUtf8 | Utf8View)
639    }
640
641    /// Returns true if this type is a List type.
642    ///
643    /// List types include List, LargeList, FixedSizeList, ListView, and LargeListView.
644    #[inline]
645    pub fn is_list(&self) -> bool {
646        use DataType::*;
647        matches!(
648            self,
649            List(_) | LargeList(_) | FixedSizeList(_, _) | ListView(_) | LargeListView(_)
650        )
651    }
652
653    /// Returns true if this type is a Binary type.
654    ///
655    /// Binary types include Binary, LargeBinary, FixedSizeBinary and BinaryView.
656    #[inline]
657    pub fn is_binary(&self) -> bool {
658        use DataType::*;
659        matches!(self, Binary | LargeBinary | FixedSizeBinary(_) | BinaryView)
660    }
661
662    /// Compares the datatype with another, ignoring nested field names
663    /// and metadata.
664    pub fn equals_datatype(&self, other: &DataType) -> bool {
665        match (&self, other) {
666            (DataType::List(a), DataType::List(b))
667            | (DataType::LargeList(a), DataType::LargeList(b))
668            | (DataType::ListView(a), DataType::ListView(b))
669            | (DataType::LargeListView(a), DataType::LargeListView(b)) => {
670                a.is_nullable() == b.is_nullable() && a.data_type().equals_datatype(b.data_type())
671            }
672            (DataType::FixedSizeList(a, a_size), DataType::FixedSizeList(b, b_size)) => {
673                a_size == b_size
674                    && a.is_nullable() == b.is_nullable()
675                    && a.data_type().equals_datatype(b.data_type())
676            }
677            (DataType::Struct(a), DataType::Struct(b)) => {
678                a.len() == b.len()
679                    && a.iter().zip(b).all(|(a, b)| {
680                        a.is_nullable() == b.is_nullable()
681                            && a.data_type().equals_datatype(b.data_type())
682                    })
683            }
684            (DataType::Map(a_field, a_is_sorted), DataType::Map(b_field, b_is_sorted)) => {
685                a_field.is_nullable() == b_field.is_nullable()
686                    && a_field.data_type().equals_datatype(b_field.data_type())
687                    && a_is_sorted == b_is_sorted
688            }
689            (DataType::Dictionary(a_key, a_value), DataType::Dictionary(b_key, b_value)) => {
690                a_key.equals_datatype(b_key) && a_value.equals_datatype(b_value)
691            }
692            (
693                DataType::RunEndEncoded(a_run_ends, a_values),
694                DataType::RunEndEncoded(b_run_ends, b_values),
695            ) => {
696                a_run_ends.is_nullable() == b_run_ends.is_nullable()
697                    && a_run_ends
698                        .data_type()
699                        .equals_datatype(b_run_ends.data_type())
700                    && a_values.is_nullable() == b_values.is_nullable()
701                    && a_values.data_type().equals_datatype(b_values.data_type())
702            }
703            (
704                DataType::Union(a_union_fields, a_union_mode),
705                DataType::Union(b_union_fields, b_union_mode),
706            ) => {
707                a_union_mode == b_union_mode
708                    && a_union_fields.len() == b_union_fields.len()
709                    && a_union_fields.iter().all(|a| {
710                        b_union_fields.iter().any(|b| {
711                            a.0 == b.0
712                                && a.1.is_nullable() == b.1.is_nullable()
713                                && a.1.data_type().equals_datatype(b.1.data_type())
714                        })
715                    })
716            }
717            _ => self == other,
718        }
719    }
720
721    /// Returns the byte width of this type if it is a primitive type
722    ///
723    /// Returns `None` if not a primitive type
724    #[inline]
725    pub fn primitive_width(&self) -> Option<usize> {
726        match self {
727            DataType::Null => None,
728            DataType::Boolean => None,
729            DataType::Int8 | DataType::UInt8 => Some(1),
730            DataType::Int16 | DataType::UInt16 | DataType::Float16 => Some(2),
731            DataType::Int32 | DataType::UInt32 | DataType::Float32 => Some(4),
732            DataType::Int64 | DataType::UInt64 | DataType::Float64 => Some(8),
733            DataType::Timestamp(_, _) => Some(8),
734            DataType::Date32 | DataType::Time32(_) => Some(4),
735            DataType::Date64 | DataType::Time64(_) => Some(8),
736            DataType::Duration(_) => Some(8),
737            DataType::Interval(IntervalUnit::YearMonth) => Some(4),
738            DataType::Interval(IntervalUnit::DayTime) => Some(8),
739            DataType::Interval(IntervalUnit::MonthDayNano) => Some(16),
740            DataType::Decimal32(_, _) => Some(4),
741            DataType::Decimal64(_, _) => Some(8),
742            DataType::Decimal128(_, _) => Some(16),
743            DataType::Decimal256(_, _) => Some(32),
744            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => None,
745            DataType::Binary | DataType::LargeBinary | DataType::BinaryView => None,
746            DataType::FixedSizeBinary(_) => None,
747            DataType::List(_)
748            | DataType::ListView(_)
749            | DataType::LargeList(_)
750            | DataType::LargeListView(_)
751            | DataType::Map(_, _) => None,
752            DataType::FixedSizeList(_, _) => None,
753            DataType::Struct(_) => None,
754            DataType::Union(_, _) => None,
755            DataType::Dictionary(_, _) => None,
756            DataType::RunEndEncoded(_, _) => None,
757        }
758    }
759
760    /// Return size of this instance in bytes.
761    ///
762    /// Includes the size of `Self`.
763    pub fn size(&self) -> usize {
764        std::mem::size_of_val(self)
765            + match self {
766                DataType::Null
767                | DataType::Boolean
768                | DataType::Int8
769                | DataType::Int16
770                | DataType::Int32
771                | DataType::Int64
772                | DataType::UInt8
773                | DataType::UInt16
774                | DataType::UInt32
775                | DataType::UInt64
776                | DataType::Float16
777                | DataType::Float32
778                | DataType::Float64
779                | DataType::Date32
780                | DataType::Date64
781                | DataType::Time32(_)
782                | DataType::Time64(_)
783                | DataType::Duration(_)
784                | DataType::Interval(_)
785                | DataType::Binary
786                | DataType::FixedSizeBinary(_)
787                | DataType::LargeBinary
788                | DataType::BinaryView
789                | DataType::Utf8
790                | DataType::LargeUtf8
791                | DataType::Utf8View
792                | DataType::Decimal32(_, _)
793                | DataType::Decimal64(_, _)
794                | DataType::Decimal128(_, _)
795                | DataType::Decimal256(_, _) => 0,
796                DataType::Timestamp(_, s) => s.as_ref().map(|s| s.len()).unwrap_or_default(),
797                DataType::List(field)
798                | DataType::ListView(field)
799                | DataType::FixedSizeList(field, _)
800                | DataType::LargeList(field)
801                | DataType::LargeListView(field)
802                | DataType::Map(field, _) => field.size(),
803                DataType::Struct(fields) => fields.size(),
804                DataType::Union(fields, _) => fields.size(),
805                DataType::Dictionary(dt1, dt2) => dt1.size() + dt2.size(),
806                DataType::RunEndEncoded(run_ends, values) => {
807                    run_ends.size() - std::mem::size_of_val(run_ends) + values.size()
808                        - std::mem::size_of_val(values)
809                }
810            }
811    }
812
813    /// Check to see if `self` is a superset of `other`
814    ///
815    /// If DataType is a nested type, then it will check to see if the nested type is a superset of the other nested type
816    /// else it will check to see if the DataType is equal to the other DataType
817    pub fn contains(&self, other: &DataType) -> bool {
818        match (self, other) {
819            (DataType::List(f1), DataType::List(f2))
820            | (DataType::LargeList(f1), DataType::LargeList(f2))
821            | (DataType::ListView(f1), DataType::ListView(f2))
822            | (DataType::LargeListView(f1), DataType::LargeListView(f2)) => f1.contains(f2),
823            (DataType::FixedSizeList(f1, s1), DataType::FixedSizeList(f2, s2)) => {
824                s1 == s2 && f1.contains(f2)
825            }
826            (DataType::Map(f1, s1), DataType::Map(f2, s2)) => s1 == s2 && f1.contains(f2),
827            (DataType::Struct(f1), DataType::Struct(f2)) => f1.contains(f2),
828            (DataType::Union(f1, s1), DataType::Union(f2, s2)) => {
829                s1 == s2
830                    && f1
831                        .iter()
832                        .all(|f1| f2.iter().any(|f2| f1.0 == f2.0 && f1.1.contains(f2.1)))
833            }
834            (DataType::Dictionary(k1, v1), DataType::Dictionary(k2, v2)) => {
835                k1.contains(k2) && v1.contains(v2)
836            }
837            _ => self == other,
838        }
839    }
840
841    /// Create a [`DataType::List`] with elements of the specified type
842    /// and nullability, and conventionally named inner [`Field`] (`"item"`).
843    ///
844    /// To specify field level metadata, construct the inner [`Field`]
845    /// directly via [`Field::new`] or [`Field::new_list_field`].
846    pub fn new_list(data_type: DataType, nullable: bool) -> Self {
847        DataType::List(Arc::new(Field::new_list_field(data_type, nullable)))
848    }
849
850    /// Create a [`DataType::LargeList`] with elements of the specified type
851    /// and nullability, and conventionally named inner [`Field`] (`"item"`).
852    ///
853    /// To specify field level metadata, construct the inner [`Field`]
854    /// directly via [`Field::new`] or [`Field::new_list_field`].
855    pub fn new_large_list(data_type: DataType, nullable: bool) -> Self {
856        DataType::LargeList(Arc::new(Field::new_list_field(data_type, nullable)))
857    }
858
859    /// Create a [`DataType::FixedSizeList`] with elements of the specified type, size
860    /// and nullability, and conventionally named inner [`Field`] (`"item"`).
861    ///
862    /// To specify field level metadata, construct the inner [`Field`]
863    /// directly via [`Field::new`] or [`Field::new_list_field`].
864    pub fn new_fixed_size_list(data_type: DataType, size: i32, nullable: bool) -> Self {
865        DataType::FixedSizeList(Arc::new(Field::new_list_field(data_type, nullable)), size)
866    }
867}
868
869/// The maximum precision for [DataType::Decimal32] values
870pub const DECIMAL32_MAX_PRECISION: u8 = 9;
871
872/// The maximum scale for [DataType::Decimal32] values
873pub const DECIMAL32_MAX_SCALE: i8 = 9;
874
875/// The maximum precision for [DataType::Decimal64] values
876pub const DECIMAL64_MAX_PRECISION: u8 = 18;
877
878/// The maximum scale for [DataType::Decimal64] values
879pub const DECIMAL64_MAX_SCALE: i8 = 18;
880
881/// The maximum precision for [DataType::Decimal128] values
882pub const DECIMAL128_MAX_PRECISION: u8 = 38;
883
884/// The maximum scale for [DataType::Decimal128] values
885pub const DECIMAL128_MAX_SCALE: i8 = 38;
886
887/// The maximum precision for [DataType::Decimal256] values
888pub const DECIMAL256_MAX_PRECISION: u8 = 76;
889
890/// The maximum scale for [DataType::Decimal256] values
891pub const DECIMAL256_MAX_SCALE: i8 = 76;
892
893/// The default scale for [DataType::Decimal32] values
894pub const DECIMAL32_DEFAULT_SCALE: i8 = 2;
895
896/// The default scale for [DataType::Decimal64] values
897pub const DECIMAL64_DEFAULT_SCALE: i8 = 6;
898
899/// The default scale for [DataType::Decimal128] and [DataType::Decimal256]
900/// values
901pub const DECIMAL_DEFAULT_SCALE: i8 = 10;
902
903#[cfg(test)]
904mod tests {
905    use super::*;
906
907    #[test]
908    #[cfg(feature = "serde")]
909    fn serde_struct_type() {
910        use std::collections::HashMap;
911
912        let kv_array = [("k".to_string(), "v".to_string())];
913        let field_metadata: HashMap<String, String> = kv_array.iter().cloned().collect();
914
915        // Non-empty map: should be converted as JSON obj { ... }
916        let first_name =
917            Field::new("first_name", DataType::Utf8, false).with_metadata(field_metadata);
918
919        // Empty map: should be omitted.
920        let last_name =
921            Field::new("last_name", DataType::Utf8, false).with_metadata(HashMap::default());
922
923        let person = DataType::Struct(Fields::from(vec![
924            first_name,
925            last_name,
926            Field::new(
927                "address",
928                DataType::Struct(Fields::from(vec![
929                    Field::new("street", DataType::Utf8, false),
930                    Field::new("zip", DataType::UInt16, false),
931                ])),
932                false,
933            ),
934        ]));
935
936        let serialized = serde_json::to_string(&person).unwrap();
937
938        // NOTE that this is testing the default (derived) serialization format, not the
939        // JSON format specified in metadata.md
940
941        assert_eq!(
942            "{\"Struct\":[\
943             {\"name\":\"first_name\",\"data_type\":\"Utf8\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{\"k\":\"v\"}},\
944             {\"name\":\"last_name\",\"data_type\":\"Utf8\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}},\
945             {\"name\":\"address\",\"data_type\":{\"Struct\":\
946             [{\"name\":\"street\",\"data_type\":\"Utf8\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}},\
947             {\"name\":\"zip\",\"data_type\":\"UInt16\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}}\
948             ]},\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}}]}",
949            serialized
950        );
951
952        let deserialized = serde_json::from_str(&serialized).unwrap();
953
954        assert_eq!(person, deserialized);
955    }
956
957    #[test]
958    fn test_list_datatype_equality() {
959        // tests that list type equality is checked while ignoring list names
960        let list_a = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
961        let list_b = DataType::List(Arc::new(Field::new("array", DataType::Int32, true)));
962        let list_c = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false)));
963        let list_d = DataType::List(Arc::new(Field::new_list_field(DataType::UInt32, true)));
964        assert!(list_a.equals_datatype(&list_b));
965        assert!(!list_a.equals_datatype(&list_c));
966        assert!(!list_b.equals_datatype(&list_c));
967        assert!(!list_a.equals_datatype(&list_d));
968
969        let list_e =
970            DataType::FixedSizeList(Arc::new(Field::new_list_field(list_a.clone(), false)), 3);
971        let list_f =
972            DataType::FixedSizeList(Arc::new(Field::new("array", list_b.clone(), false)), 3);
973        let list_g = DataType::FixedSizeList(
974            Arc::new(Field::new_list_field(DataType::FixedSizeBinary(3), true)),
975            3,
976        );
977        assert!(list_e.equals_datatype(&list_f));
978        assert!(!list_e.equals_datatype(&list_g));
979        assert!(!list_f.equals_datatype(&list_g));
980
981        let list_h = DataType::Struct(Fields::from(vec![Field::new("f1", list_e, true)]));
982        let list_i = DataType::Struct(Fields::from(vec![Field::new("f1", list_f.clone(), true)]));
983        let list_j = DataType::Struct(Fields::from(vec![Field::new("f1", list_f.clone(), false)]));
984        let list_k = DataType::Struct(Fields::from(vec![
985            Field::new("f1", list_f.clone(), false),
986            Field::new("f2", list_g.clone(), false),
987            Field::new("f3", DataType::Utf8, true),
988        ]));
989        let list_l = DataType::Struct(Fields::from(vec![
990            Field::new("ff1", list_f.clone(), false),
991            Field::new("ff2", list_g.clone(), false),
992            Field::new("ff3", DataType::LargeUtf8, true),
993        ]));
994        let list_m = DataType::Struct(Fields::from(vec![
995            Field::new("ff1", list_f, false),
996            Field::new("ff2", list_g, false),
997            Field::new("ff3", DataType::Utf8, true),
998        ]));
999        assert!(list_h.equals_datatype(&list_i));
1000        assert!(!list_h.equals_datatype(&list_j));
1001        assert!(!list_k.equals_datatype(&list_l));
1002        assert!(list_k.equals_datatype(&list_m));
1003
1004        let list_n = DataType::Map(Arc::new(Field::new("f1", list_a.clone(), true)), true);
1005        let list_o = DataType::Map(Arc::new(Field::new("f2", list_b.clone(), true)), true);
1006        let list_p = DataType::Map(Arc::new(Field::new("f2", list_b.clone(), true)), false);
1007        let list_q = DataType::Map(Arc::new(Field::new("f2", list_c.clone(), true)), true);
1008        let list_r = DataType::Map(Arc::new(Field::new("f1", list_a.clone(), false)), true);
1009
1010        assert!(list_n.equals_datatype(&list_o));
1011        assert!(!list_n.equals_datatype(&list_p));
1012        assert!(!list_n.equals_datatype(&list_q));
1013        assert!(!list_n.equals_datatype(&list_r));
1014
1015        let list_s = DataType::Dictionary(Box::new(DataType::UInt8), Box::new(list_a));
1016        let list_t = DataType::Dictionary(Box::new(DataType::UInt8), Box::new(list_b.clone()));
1017        let list_u = DataType::Dictionary(Box::new(DataType::Int8), Box::new(list_b));
1018        let list_v = DataType::Dictionary(Box::new(DataType::UInt8), Box::new(list_c));
1019
1020        assert!(list_s.equals_datatype(&list_t));
1021        assert!(!list_s.equals_datatype(&list_u));
1022        assert!(!list_s.equals_datatype(&list_v));
1023
1024        let union_a = DataType::Union(
1025            UnionFields::try_new(
1026                vec![1, 2],
1027                vec![
1028                    Field::new("f1", DataType::Utf8, false),
1029                    Field::new("f2", DataType::UInt8, false),
1030                ],
1031            )
1032            .unwrap(),
1033            UnionMode::Sparse,
1034        );
1035        let union_b = DataType::Union(
1036            UnionFields::try_new(
1037                vec![1, 2],
1038                vec![
1039                    Field::new("ff1", DataType::Utf8, false),
1040                    Field::new("ff2", DataType::UInt8, false),
1041                ],
1042            )
1043            .unwrap(),
1044            UnionMode::Sparse,
1045        );
1046        let union_c = DataType::Union(
1047            UnionFields::try_new(
1048                vec![2, 1],
1049                vec![
1050                    Field::new("fff2", DataType::UInt8, false),
1051                    Field::new("fff1", DataType::Utf8, false),
1052                ],
1053            )
1054            .unwrap(),
1055            UnionMode::Sparse,
1056        );
1057        let union_d = DataType::Union(
1058            UnionFields::try_new(
1059                vec![2, 1],
1060                vec![
1061                    Field::new("fff1", DataType::Int8, false),
1062                    Field::new("fff2", DataType::UInt8, false),
1063                ],
1064            )
1065            .unwrap(),
1066            UnionMode::Sparse,
1067        );
1068        let union_e = DataType::Union(
1069            UnionFields::try_new(
1070                vec![1, 2],
1071                vec![
1072                    Field::new("f1", DataType::Utf8, true),
1073                    Field::new("f2", DataType::UInt8, false),
1074                ],
1075            )
1076            .unwrap(),
1077            UnionMode::Sparse,
1078        );
1079
1080        assert!(union_a.equals_datatype(&union_b));
1081        assert!(union_a.equals_datatype(&union_c));
1082        assert!(!union_a.equals_datatype(&union_d));
1083        assert!(!union_a.equals_datatype(&union_e));
1084
1085        let list_w = DataType::RunEndEncoded(
1086            Arc::new(Field::new("f1", DataType::Int64, true)),
1087            Arc::new(Field::new("f2", DataType::Utf8, true)),
1088        );
1089        let list_x = DataType::RunEndEncoded(
1090            Arc::new(Field::new("ff1", DataType::Int64, true)),
1091            Arc::new(Field::new("ff2", DataType::Utf8, true)),
1092        );
1093        let list_y = DataType::RunEndEncoded(
1094            Arc::new(Field::new("ff1", DataType::UInt16, true)),
1095            Arc::new(Field::new("ff2", DataType::Utf8, true)),
1096        );
1097        let list_z = DataType::RunEndEncoded(
1098            Arc::new(Field::new("f1", DataType::Int64, false)),
1099            Arc::new(Field::new("f2", DataType::Utf8, true)),
1100        );
1101
1102        assert!(list_w.equals_datatype(&list_x));
1103        assert!(!list_w.equals_datatype(&list_y));
1104        assert!(!list_w.equals_datatype(&list_z));
1105    }
1106
1107    #[test]
1108    fn create_struct_type() {
1109        let _person = DataType::Struct(Fields::from(vec![
1110            Field::new("first_name", DataType::Utf8, false),
1111            Field::new("last_name", DataType::Utf8, false),
1112            Field::new(
1113                "address",
1114                DataType::Struct(Fields::from(vec![
1115                    Field::new("street", DataType::Utf8, false),
1116                    Field::new("zip", DataType::UInt16, false),
1117                ])),
1118                false,
1119            ),
1120        ]));
1121    }
1122
1123    #[test]
1124    fn test_nested() {
1125        let list = DataType::List(Arc::new(Field::new("foo", DataType::Utf8, true)));
1126        let list_view = DataType::ListView(Arc::new(Field::new("foo", DataType::Utf8, true)));
1127        let large_list_view =
1128            DataType::LargeListView(Arc::new(Field::new("foo", DataType::Utf8, true)));
1129
1130        assert!(!DataType::is_nested(&DataType::Boolean));
1131        assert!(!DataType::is_nested(&DataType::Int32));
1132        assert!(!DataType::is_nested(&DataType::Utf8));
1133        assert!(DataType::is_nested(&list));
1134        assert!(DataType::is_nested(&list_view));
1135        assert!(DataType::is_nested(&large_list_view));
1136
1137        assert!(!DataType::is_nested(&DataType::Dictionary(
1138            Box::new(DataType::Int32),
1139            Box::new(DataType::Boolean)
1140        )));
1141        assert!(!DataType::is_nested(&DataType::Dictionary(
1142            Box::new(DataType::Int32),
1143            Box::new(DataType::Int64)
1144        )));
1145        assert!(!DataType::is_nested(&DataType::Dictionary(
1146            Box::new(DataType::Int32),
1147            Box::new(DataType::LargeUtf8)
1148        )));
1149        assert!(DataType::is_nested(&DataType::Dictionary(
1150            Box::new(DataType::Int32),
1151            Box::new(list)
1152        )));
1153    }
1154
1155    #[test]
1156    fn test_integer() {
1157        // is_integer
1158        assert!(DataType::is_integer(&DataType::Int32));
1159        assert!(DataType::is_integer(&DataType::UInt64));
1160        assert!(!DataType::is_integer(&DataType::Float16));
1161
1162        // is_signed_integer
1163        assert!(DataType::is_signed_integer(&DataType::Int32));
1164        assert!(!DataType::is_signed_integer(&DataType::UInt64));
1165        assert!(!DataType::is_signed_integer(&DataType::Float16));
1166
1167        // is_unsigned_integer
1168        assert!(!DataType::is_unsigned_integer(&DataType::Int32));
1169        assert!(DataType::is_unsigned_integer(&DataType::UInt64));
1170        assert!(!DataType::is_unsigned_integer(&DataType::Float16));
1171
1172        // is_dictionary_key_type
1173        assert!(DataType::is_dictionary_key_type(&DataType::Int32));
1174        assert!(DataType::is_dictionary_key_type(&DataType::UInt64));
1175        assert!(!DataType::is_dictionary_key_type(&DataType::Float16));
1176    }
1177
1178    #[test]
1179    fn test_string() {
1180        assert!(DataType::is_string(&DataType::Utf8));
1181        assert!(DataType::is_string(&DataType::LargeUtf8));
1182        assert!(DataType::is_string(&DataType::Utf8View));
1183        assert!(!DataType::is_string(&DataType::Int32));
1184    }
1185
1186    #[test]
1187    fn test_floating() {
1188        assert!(DataType::is_floating(&DataType::Float16));
1189        assert!(!DataType::is_floating(&DataType::Int32));
1190    }
1191
1192    #[test]
1193    fn test_decimal() {
1194        assert!(DataType::is_decimal(&DataType::Decimal32(4, 2)));
1195        assert!(DataType::is_decimal(&DataType::Decimal64(4, 2)));
1196        assert!(DataType::is_decimal(&DataType::Decimal128(4, 2)));
1197        assert!(DataType::is_decimal(&DataType::Decimal256(4, 2)));
1198        assert!(!DataType::is_decimal(&DataType::Float16));
1199    }
1200
1201    #[test]
1202    fn test_datatype_is_null() {
1203        assert!(DataType::is_null(&DataType::Null));
1204        assert!(!DataType::is_null(&DataType::Int32));
1205    }
1206
1207    #[test]
1208    fn test_is_list() {
1209        assert!(DataType::is_list(&DataType::new_list(
1210            DataType::Int16,
1211            true
1212        )));
1213        assert!(DataType::is_list(&DataType::new_large_list(
1214            DataType::Int16,
1215            true
1216        )));
1217        assert!(DataType::is_list(&DataType::new_fixed_size_list(
1218            DataType::Int16,
1219            5,
1220            true
1221        )));
1222        assert!(DataType::is_list(&DataType::ListView(Arc::new(
1223            Field::new("f", DataType::Int16, true)
1224        ))));
1225        assert!(DataType::is_list(&DataType::LargeListView(Arc::new(
1226            Field::new("f", DataType::Int16, true)
1227        ))));
1228        assert!(!DataType::is_list(&DataType::Binary));
1229    }
1230
1231    #[test]
1232    fn test_is_binary() {
1233        assert!(DataType::is_binary(&DataType::Binary));
1234        assert!(DataType::is_binary(&DataType::LargeBinary));
1235        assert!(DataType::is_binary(&DataType::BinaryView));
1236        assert!(!DataType::is_list(&DataType::Utf8View));
1237    }
1238
1239    #[test]
1240    fn size_should_not_regress() {
1241        assert_eq!(std::mem::size_of::<DataType>(), 24);
1242    }
1243
1244    #[test]
1245    #[should_panic(expected = "duplicate type id: 1")]
1246    fn test_union_with_duplicated_type_id() {
1247        let type_ids = vec![1, 1];
1248        let _union = DataType::Union(
1249            UnionFields::try_new(
1250                type_ids,
1251                vec![
1252                    Field::new("f1", DataType::Int32, false),
1253                    Field::new("f2", DataType::Utf8, false),
1254                ],
1255            )
1256            .unwrap(),
1257            UnionMode::Dense,
1258        );
1259    }
1260
1261    #[test]
1262    fn test_try_from_str() {
1263        let data_type: DataType = "Int32".try_into().unwrap();
1264        assert_eq!(data_type, DataType::Int32);
1265    }
1266
1267    #[test]
1268    fn test_from_str() {
1269        let data_type: DataType = "UInt64".parse().unwrap();
1270        assert_eq!(data_type, DataType::UInt64);
1271    }
1272
1273    #[test]
1274    #[cfg_attr(miri, ignore)] // Can't handle the inlined strings of the assert_debug_snapshot macro
1275    fn test_debug_format_field() {
1276        // Make sure the `Debug` formatting of `DataType` is readable and not too long
1277        insta::assert_debug_snapshot!(DataType::new_list(DataType::Int8, false), @r"
1278        List(
1279            Field {
1280                data_type: Int8,
1281            },
1282        )
1283        ");
1284    }
1285}