1use std::cmp::Ordering;
2use std::fmt::Debug;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
20pub enum DataType {
21 Null,
23 Bool,
25 Int8,
27 Int16,
29 Int32,
31 Int64,
33 Int128,
35 UInt8,
37 UInt16,
39 UInt32,
41 UInt64,
43 UInt128,
45 Float32,
47 Float64,
49 String,
51 List(Box<DataType>),
53}
54
55impl DataType {
56 pub fn is_float(&self) -> bool {
58 matches!(self, DataType::Float32 | DataType::Float64)
59 }
60
61 pub fn is_integer(&self) -> bool {
63 matches!(
64 self,
65 DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Int128 |
66 DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 | DataType::UInt128
67 )
68 }
69
70 pub fn is_numeric(&self) -> bool {
72 matches!(
73 self,
74 DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 |
75 DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 |
76 DataType::Float32 | DataType::Float64
77 )
78 }
79}
80
81impl Ord for DataType {
82 fn cmp(&self, other: &Self) -> Ordering {
83 fn order_index(dt: &DataType) -> i32 {
84 match dt {
85 DataType::Null => 0,
86 DataType::Bool => 1,
87 DataType::Int8 => 10,
88 DataType::Int16 => 11,
89 DataType::Int32 => 12,
90 DataType::Int64 => 13,
91 DataType::Int128 => 14,
92 DataType::UInt8 => 20,
93 DataType::UInt16 => 21,
94 DataType::UInt32 => 22,
95 DataType::UInt64 => 23,
96 DataType::UInt128 => 24,
97 DataType::Float32 => 30,
98 DataType::Float64 => 31,
99 DataType::String => 40,
100 DataType::List(_) => 100,
101 }
102 }
103
104 match order_index(self).cmp(&order_index(other)) {
105 Ordering::Equal => {
106 match (self, other) {
107 (DataType::List(a), DataType::List(b)) => a.cmp(b),
108 _ => Ordering::Equal,
109 }
110 }
111 order => order,
112 }
113 }
114}
115
116impl PartialOrd for DataType {
117 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
118 Some(self.cmp(other))
119 }
120}
121
122pub trait DataTypeTrait: Debug + Clone + Send + Sync + 'static {
134 const DTYPE: DataType;
136
137 fn as_dtype(&self) -> DataType;
141}
142
143macro_rules! impl_datatype_trait {
145 ($prim_type: ty, $dtype_variant: ident) => {
146 impl DataTypeTrait for $prim_type where $prim_type: Debug + Clone {
147 const DTYPE: DataType = DataType::$dtype_variant;
148
149 fn as_dtype(&self) -> DataType {
150 Self::DTYPE
151 }
152 }
153 };
154}
155
156impl_datatype_trait!(i8, Int8);
158impl_datatype_trait!(i16, Int16);
159impl_datatype_trait!(i32, Int32);
160impl_datatype_trait!(i64, Int64);
161impl_datatype_trait!(u8, UInt8);
162impl_datatype_trait!(u16, UInt16);
163impl_datatype_trait!(u32, UInt32);
164impl_datatype_trait!(u64, UInt64);
165
166impl_datatype_trait!(f32, Float32);
168impl_datatype_trait!(f64, Float64);
169
170impl_datatype_trait!(bool, Bool);
172
173impl DataTypeTrait for String {
175 const DTYPE: DataType = DataType::String;
176
177 fn as_dtype(&self) -> DataType {
178 Self::DTYPE
179 }
180}