c_api_tools/
types.rs

1//! Useful conversion types.
2
3/// Representation of scalar numeric type information
4/// as runtime parameter.
5#[derive(Debug, Clone, Copy, PartialEq)]
6#[repr(u8)]
7pub enum DType {
8    /// Float 32
9    F32,
10    /// Float 64
11    F64,
12    /// Complex 32
13    C32,
14    /// Complex 64
15    C64,
16    /// Unsigned int 8
17    U8,
18    /// Unsigned int 32
19    U32,
20    /// Unsigned int 64
21    U64,
22    /// Int 8
23    I8,
24    /// Int 32
25    I32,
26    /// Int 64
27    I64,
28    /// Undefined type
29    Undefined,
30}
31
32impl DType {
33    /// Return true of type is real.
34    pub fn is_real(&self) -> bool {
35        matches!(
36            self,
37            DType::F32
38                | DType::F64
39                | DType::U8
40                | DType::U32
41                | DType::U64
42                | DType::I8
43                | DType::I32
44                | DType::I64,
45        )
46    }
47
48    /// Return true if type is complex.
49    pub fn is_complex(&self) -> bool {
50        matches!(self, DType::C32 | DType::C64)
51    }
52
53    /// Return the associated real type.
54    pub fn real_type(&self) -> DType {
55        match self {
56            DType::C32 => DType::F32,
57            DType::C64 => DType::F64,
58            _ => *self,
59        }
60    }
61
62    /// Return the associated complex type.
63    ///
64    /// If there is no associated complex type `DType::Undefined` is returned.
65    pub fn complex_type(&self) -> DType {
66        match self {
67            DType::F32 => DType::C32,
68            DType::F64 => DType::C64,
69            _ => DType::Undefined,
70        }
71    }
72}
73
74/// Runtime numeric type information.
75pub trait DTypeIdentifier {
76    /// Return runtime numeric type information.
77    fn dtype() -> DType;
78}
79
80impl DTypeIdentifier for f32 {
81    fn dtype() -> DType {
82        DType::F32
83    }
84}
85
86impl DTypeIdentifier for f64 {
87    fn dtype() -> DType {
88        DType::F64
89    }
90}
91
92impl DTypeIdentifier for num::complex::Complex<f32> {
93    fn dtype() -> DType {
94        DType::C32
95    }
96}
97
98impl DTypeIdentifier for num::complex::Complex<f64> {
99    fn dtype() -> DType {
100        DType::C64
101    }
102}
103
104impl DTypeIdentifier for u8 {
105    fn dtype() -> DType {
106        DType::U8
107    }
108}
109
110impl DTypeIdentifier for u32 {
111    fn dtype() -> DType {
112        DType::U32
113    }
114}
115
116impl DTypeIdentifier for u64 {
117    fn dtype() -> DType {
118        DType::U64
119    }
120}
121
122impl DTypeIdentifier for i8 {
123    fn dtype() -> DType {
124        DType::I8
125    }
126}
127
128impl DTypeIdentifier for i32 {
129    fn dtype() -> DType {
130        DType::I32
131    }
132}
133
134impl DTypeIdentifier for i64 {
135    fn dtype() -> DType {
136        DType::I64
137    }
138}