Skip to main content

qubit_common/lang/
data_type.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Data Type Definitions (Language Layer)
10//!
11//! Provides cross-module reusable common data type enum `DataType` and type mapping `DataTypeOf`.
12//!
13//! # Author
14//!
15//! Haixing Hu
16
17use bigdecimal::BigDecimal;
18use chrono::{
19    DateTime,
20    NaiveDate,
21    NaiveDateTime,
22    NaiveTime,
23    Utc,
24};
25use num_bigint::BigInt;
26use serde::{
27    Deserialize,
28    Serialize,
29};
30use serde_json;
31use std::collections::HashMap;
32use std::time::Duration;
33use url::Url;
34
35/// Universal data type enumeration for cross-module type representation
36///
37/// Defines all basic data types and composite types supported by the system.
38/// This enum provides a unified way to represent and work with different data types
39/// across various modules and components.
40///
41/// `DataType` serves as a bridge between Rust's type system and runtime type
42/// information, enabling dynamic type handling, serialization, validation,
43/// and other type-aware operations.
44///
45/// # Features
46///
47/// - **Comprehensive Coverage**: Supports all basic Rust types plus common third-party types
48/// - **String Representation**: Each variant has a consistent string representation
49/// - **Serialization Support**: Implements `Serialize` and `Deserialize` for JSON/YAML support
50/// - **Type Mapping**: Works with `DataTypeOf` trait for compile-time type mapping
51///
52/// # Use Cases
53///
54/// - **Dynamic Type Handling**: Runtime type checking and conversion
55/// - **Serialization/Deserialization**: Type-aware data format conversion
56/// - **Validation Systems**: Type-based input validation
57/// - **Generic Programming**: Type-safe generic operations
58/// - **API Documentation**: Automatic type information generation
59///
60/// # Examples
61///
62/// ## Basic Usage
63///
64/// ```rust,ignore
65/// use qubit_common::lang::DataType;
66///
67/// let data_type = DataType::Int32;
68/// assert_eq!(data_type.to_string(), "int32");
69/// assert_eq!(data_type.as_str(), "int32");
70/// ```
71///
72/// ## Type Checking
73///
74/// ```rust,ignore
75/// use qubit_common::lang::DataType;
76///
77/// fn is_numeric(data_type: DataType) -> bool {
78///     matches!(data_type,
79///         DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Int128 |
80///         DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 | DataType::UInt128 |
81///         DataType::Float32 | DataType::Float64 | DataType::BigInteger | DataType::BigDecimal
82///     )
83/// }
84///
85/// assert!(is_numeric(DataType::Int32));
86/// assert!(!is_numeric(DataType::String));
87/// ```
88///
89/// ## Serialization
90///
91/// ```rust,ignore
92/// use qubit_common::lang::DataType;
93/// use serde_json;
94///
95/// let data_type = DataType::Float64;
96/// let json = serde_json::to_string(&data_type).unwrap();
97/// assert_eq!(json, "\"float64\"");
98///
99/// let deserialized: DataType = serde_json::from_str(&json).unwrap();
100/// assert_eq!(deserialized, DataType::Float64);
101/// ```
102///
103/// # Author
104///
105/// Haixing Hu
106///
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
108pub enum DataType {
109    /// Boolean type
110    Bool,
111    /// Character type
112    Char,
113    /// 8-bit signed integer
114    Int8,
115    /// 16-bit signed integer
116    Int16,
117    /// 32-bit signed integer
118    Int32,
119    /// 64-bit signed integer
120    Int64,
121    /// 128-bit signed integer
122    Int128,
123    /// 8-bit unsigned integer
124    UInt8,
125    /// 16-bit unsigned integer
126    UInt16,
127    /// 32-bit unsigned integer
128    UInt32,
129    /// 64-bit unsigned integer
130    UInt64,
131    /// 128-bit unsigned integer
132    UInt128,
133    /// 32-bit floating point number
134    Float32,
135    /// 64-bit floating point number
136    Float64,
137    /// String type
138    String,
139    /// Date type (NaiveDate)
140    Date,
141    /// Time type (NaiveTime)
142    Time,
143    /// DateTime type (NaiveDateTime)
144    DateTime,
145    /// UTC time point (equivalent to Java Instant) (`DateTime<Utc>`)
146    Instant,
147    /// Big integer type (BigInt)
148    BigInteger,
149    /// Big decimal type (BigDecimal)
150    BigDecimal,
151    /// Platform-dependent signed integer (isize)
152    IntSize,
153    /// Platform-dependent unsigned integer (usize)
154    UIntSize,
155    /// Duration type (std::time::Duration)
156    Duration,
157    /// URL type (url::Url)
158    Url,
159    /// String map type (HashMap<String, String>)
160    StringMap,
161    /// JSON value type (serde_json::Value)
162    Json,
163}
164
165impl DataType {
166    /// Get the string representation of the data type
167    ///
168    /// # Returns
169    ///
170    /// Returns the name string of the data type
171    ///
172    /// # Examples
173    ///
174    /// ```rust,ignore
175    /// use qubit_common::lang::DataType;
176    ///
177    /// assert_eq!(DataType::Int32.as_str(), "int32");
178    /// assert_eq!(DataType::String.as_str(), "string");
179    /// ```
180    pub const fn as_str(&self) -> &'static str {
181        match self {
182            DataType::Bool => "bool",
183            DataType::Char => "char",
184            DataType::Int8 => "int8",
185            DataType::Int16 => "int16",
186            DataType::Int32 => "int32",
187            DataType::Int64 => "int64",
188            DataType::Int128 => "int128",
189            DataType::UInt8 => "uint8",
190            DataType::UInt16 => "uint16",
191            DataType::UInt32 => "uint32",
192            DataType::UInt64 => "uint64",
193            DataType::UInt128 => "uint128",
194            DataType::Float32 => "float32",
195            DataType::Float64 => "float64",
196            DataType::String => "string",
197            DataType::Date => "date",
198            DataType::Time => "time",
199            DataType::DateTime => "datetime",
200            DataType::Instant => "instant",
201            DataType::BigInteger => "biginteger",
202            DataType::BigDecimal => "bigdecimal",
203            DataType::IntSize => "intsize",
204            DataType::UIntSize => "uintsize",
205            DataType::Duration => "duration",
206            DataType::Url => "url",
207            DataType::StringMap => "stringmap",
208            DataType::Json => "json",
209        }
210    }
211}
212
213impl std::fmt::Display for DataType {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        write!(f, "{}", self.as_str())
216    }
217}
218
219// =============================================================================
220// Compile-time mapping from types to DataType
221// =============================================================================
222
223/// Marker trait for mapping concrete Rust types to `DataType`
224///
225/// Provides an associated constant to know the corresponding `DataType` at compile time,
226/// facilitating static type-to-data-type queries in generic code based on `T`.
227///
228/// This trait enables compile-time type-to-data-type mapping, allowing generic code
229/// to determine the appropriate `DataType` for any type that implements this trait.
230/// This is particularly useful for serialization frameworks, validation systems,
231/// and other scenarios where you need to know the data type at compile time.
232///
233/// # Usage
234///
235/// The trait is automatically implemented for all basic Rust types and common
236/// third-party types. You can use it in generic functions to determine the
237/// corresponding `DataType` for any type.
238///
239/// # Examples
240///
241/// ## Basic Usage
242///
243/// ```rust,ignore
244/// use qubit_common::lang::{DataType, DataTypeOf};
245///
246/// // Get the data type for a specific type
247/// assert_eq!(i32::DATA_TYPE, DataType::Int32);
248/// assert_eq!(String::DATA_TYPE, DataType::String);
249/// assert_eq!(bool::DATA_TYPE, DataType::Bool);
250/// ```
251///
252/// ## Generic Function Example
253///
254/// ```rust,ignore
255/// use qubit_common::lang::{DataType, DataTypeOf};
256///
257/// fn get_type_name<T: DataTypeOf>() -> &'static str {
258///     T::DATA_TYPE.as_str()
259/// }
260///
261/// assert_eq!(get_type_name::<i32>(), "int32");
262/// assert_eq!(get_type_name::<String>(), "string");
263/// assert_eq!(get_type_name::<f64>(), "float64");
264/// ```
265///
266/// ## Generic Value Container Example
267///
268/// ```rust,ignore
269/// use qubit_common::lang::{DataType, DataTypeOf};
270///
271/// struct TypedValue<T: DataTypeOf> {
272///     value: T,
273///     data_type: DataType,
274/// }
275///
276/// impl<T: DataTypeOf> TypedValue<T> {
277///     fn new(value: T) -> Self {
278///         Self {
279///             value,
280///             data_type: T::DATA_TYPE,
281///         }
282///     }
283///
284///     fn get_data_type(&self) -> DataType {
285///         self.data_type
286///     }
287/// }
288///
289/// let typed_value = TypedValue::new(42i32);
290/// assert_eq!(typed_value.get_data_type(), DataType::Int32);
291/// ```
292///
293/// ## Type Validation Example
294///
295/// ```rust,ignore
296/// use qubit_common::lang::{DataType, DataTypeOf};
297///
298/// fn validate_numeric_type<T: DataTypeOf>() -> bool {
299///     matches!(T::DATA_TYPE,
300///         DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Int128 |
301///         DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 | DataType::UInt128 |
302///         DataType::Float32 | DataType::Float64 | DataType::BigInteger | DataType::BigDecimal
303///     )
304/// }
305///
306/// assert!(validate_numeric_type::<i32>());
307/// assert!(validate_numeric_type::<f64>());
308/// assert!(!validate_numeric_type::<String>());
309/// ```
310///
311/// # Supported Types
312///
313/// The following types have `DataTypeOf` implementations:
314///
315/// - **Basic Types**: `bool`, `char`, `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`, `f32`, `f64`
316/// - **String Types**: `String`
317/// - **Date/Time Types**: `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
318/// - **Big Number Types**: `BigInt`, `BigDecimal`
319/// - **URL**: `url::Url`
320///
321/// # Author
322///
323/// Haixing Hu
324///
325pub trait DataTypeOf {
326    /// The `DataType` corresponding to this Rust type
327    const DATA_TYPE: DataType;
328}
329
330// Basic scalar types
331impl DataTypeOf for bool {
332    const DATA_TYPE: DataType = DataType::Bool;
333}
334impl DataTypeOf for char {
335    const DATA_TYPE: DataType = DataType::Char;
336}
337impl DataTypeOf for i8 {
338    const DATA_TYPE: DataType = DataType::Int8;
339}
340impl DataTypeOf for i16 {
341    const DATA_TYPE: DataType = DataType::Int16;
342}
343impl DataTypeOf for i32 {
344    const DATA_TYPE: DataType = DataType::Int32;
345}
346impl DataTypeOf for i64 {
347    const DATA_TYPE: DataType = DataType::Int64;
348}
349impl DataTypeOf for i128 {
350    const DATA_TYPE: DataType = DataType::Int128;
351}
352impl DataTypeOf for u8 {
353    const DATA_TYPE: DataType = DataType::UInt8;
354}
355impl DataTypeOf for u16 {
356    const DATA_TYPE: DataType = DataType::UInt16;
357}
358impl DataTypeOf for u32 {
359    const DATA_TYPE: DataType = DataType::UInt32;
360}
361impl DataTypeOf for u64 {
362    const DATA_TYPE: DataType = DataType::UInt64;
363}
364impl DataTypeOf for u128 {
365    const DATA_TYPE: DataType = DataType::UInt128;
366}
367impl DataTypeOf for f32 {
368    const DATA_TYPE: DataType = DataType::Float32;
369}
370impl DataTypeOf for f64 {
371    const DATA_TYPE: DataType = DataType::Float64;
372}
373
374// String types
375impl DataTypeOf for String {
376    const DATA_TYPE: DataType = DataType::String;
377}
378
379// Date and time types (chrono)
380impl DataTypeOf for NaiveDate {
381    const DATA_TYPE: DataType = DataType::Date;
382}
383impl DataTypeOf for NaiveTime {
384    const DATA_TYPE: DataType = DataType::Time;
385}
386impl DataTypeOf for NaiveDateTime {
387    const DATA_TYPE: DataType = DataType::DateTime;
388}
389impl DataTypeOf for DateTime<Utc> {
390    const DATA_TYPE: DataType = DataType::Instant;
391}
392
393// Big number types
394impl DataTypeOf for BigInt {
395    const DATA_TYPE: DataType = DataType::BigInteger;
396}
397impl DataTypeOf for BigDecimal {
398    const DATA_TYPE: DataType = DataType::BigDecimal;
399}
400
401// Platform-dependent integer types
402impl DataTypeOf for isize {
403    const DATA_TYPE: DataType = DataType::IntSize;
404}
405impl DataTypeOf for usize {
406    const DATA_TYPE: DataType = DataType::UIntSize;
407}
408
409// Standard library types
410impl DataTypeOf for Duration {
411    const DATA_TYPE: DataType = DataType::Duration;
412}
413
414impl DataTypeOf for Url {
415    const DATA_TYPE: DataType = DataType::Url;
416}
417
418// String map type
419impl DataTypeOf for HashMap<String, String> {
420    const DATA_TYPE: DataType = DataType::StringMap;
421}
422
423// JSON value type
424impl DataTypeOf for serde_json::Value {
425    const DATA_TYPE: DataType = DataType::Json;
426}