use num_complex::Complex;
pub type Complex32 = Complex<f32>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Dtype {
F32,
F16,
}
impl Dtype {
pub const fn size(self) -> usize {
match self {
Dtype::F32 => 4,
Dtype::F16 => 2,
}
}
pub const fn as_str(self) -> &'static str {
match self {
Dtype::F32 => "float32",
Dtype::F16 => "float16",
}
}
}
impl std::str::FromStr for Dtype {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"float32" | "f32" | "fp32" => Ok(Dtype::F32),
"float16" | "f16" | "fp16" | "half" => Ok(Dtype::F16),
other => Err(format!("unknown dtype '{other}' (float32|float16)")),
}
}
}
pub trait Element: Copy + Send + Sync + 'static {
const DTYPE: Dtype;
fn zero() -> Self;
}
impl Element for f32 {
const DTYPE: Dtype = Dtype::F32;
fn zero() -> Self {
0.0
}
}
impl Element for half::f16 {
const DTYPE: Dtype = Dtype::F16;
fn zero() -> Self {
half::f16::from_f32_const(0.0)
}
}
#[cfg(test)]
mod tests {
use super::Dtype;
#[test]
fn dtype_from_str_aliases() {
for s in ["float32", "f32", "FP32", " Float32 "] {
assert_eq!(s.parse::<Dtype>().unwrap(), Dtype::F32, "{s}");
}
for s in ["float16", "f16", "FP16", "half"] {
assert_eq!(s.parse::<Dtype>().unwrap(), Dtype::F16, "{s}");
}
assert!("float8".parse::<Dtype>().is_err());
assert_eq!(Dtype::F16.as_str().parse::<Dtype>().unwrap(), Dtype::F16);
}
}