use std::fmt;
use half::{bf16, f16};
use crate::complex::{c64, c128};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub enum DType {
Bool,
I8,
I16,
I32,
I64,
U8,
U16,
U32,
U64,
F16,
BF16,
F32,
F64,
C64,
C128,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum DTypeKind {
Bool,
SignedInt,
UnsignedInt,
Float,
Complex,
}
impl DType {
pub const ALL: [DType; 15] = [
DType::Bool,
DType::I8,
DType::I16,
DType::I32,
DType::I64,
DType::U8,
DType::U16,
DType::U32,
DType::U64,
DType::F16,
DType::BF16,
DType::F32,
DType::F64,
DType::C64,
DType::C128,
];
pub fn kind(self) -> DTypeKind {
match self {
DType::Bool => DTypeKind::Bool,
DType::I8 | DType::I16 | DType::I32 | DType::I64 => DTypeKind::SignedInt,
DType::U8 | DType::U16 | DType::U32 | DType::U64 => DTypeKind::UnsignedInt,
DType::F16 | DType::BF16 | DType::F32 | DType::F64 => DTypeKind::Float,
DType::C64 | DType::C128 => DTypeKind::Complex,
}
}
pub fn is_float(self) -> bool {
self.kind() == DTypeKind::Float
}
pub fn is_complex(self) -> bool {
self.kind() == DTypeKind::Complex
}
pub fn is_inexact(self) -> bool {
matches!(self.kind(), DTypeKind::Float | DTypeKind::Complex)
}
pub fn real_dtype(self) -> DType {
match self {
DType::C64 => DType::F32,
DType::C128 => DType::F64,
d => d,
}
}
pub fn complex_dtype(self) -> Option<DType> {
match self {
DType::F32 | DType::C64 => Some(DType::C64),
DType::F64 | DType::C128 => Some(DType::C128),
_ => None,
}
}
pub fn is_int(self) -> bool {
matches!(self.kind(), DTypeKind::SignedInt | DTypeKind::UnsignedInt)
}
pub fn size_in_bytes(self) -> usize {
match self {
DType::Bool | DType::I8 | DType::U8 => 1,
DType::I16 | DType::U16 | DType::F16 | DType::BF16 => 2,
DType::I32 | DType::U32 | DType::F32 => 4,
DType::I64 | DType::U64 | DType::F64 | DType::C64 => 8,
DType::C128 => 16,
}
}
pub fn name(self) -> &'static str {
match self {
DType::Bool => "bool",
DType::I8 => "i8",
DType::I16 => "i16",
DType::I32 => "i32",
DType::I64 => "i64",
DType::U8 => "u8",
DType::U16 => "u16",
DType::U32 => "u32",
DType::U64 => "u64",
DType::F16 => "f16",
DType::BF16 => "bf16",
DType::F32 => "f32",
DType::F64 => "f64",
DType::C64 => "c64",
DType::C128 => "c128",
}
}
pub fn from_name(name: &str) -> Option<DType> {
DType::ALL.into_iter().find(|d| d.name() == name)
}
}
impl fmt::Display for DType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Value {
Bool(bool),
Int(i64),
UInt(u64),
Float(f64),
Complex(f64, f64),
}
mod sealed {
pub trait Sealed {}
}
pub trait Element:
Copy
+ Send
+ Sync
+ PartialEq
+ PartialOrd
+ Default
+ fmt::Debug
+ 'static
+ sealed::Sealed
+ crate::ops::Ops
+ crate::buffer::BufferElement
{
const DTYPE: DType;
type Real: Element;
fn re(self) -> Self::Real;
fn im(self) -> Self::Real;
fn from_parts(re: Self::Real, im: Self::Real) -> Self;
fn to_value(self) -> Value;
fn from_value(v: Value) -> Self;
fn write_bytes(self, out: &mut Vec<u8>);
fn read_bytes(bytes: &[u8]) -> Self;
fn to_bits(self) -> u64;
fn from_bits(bits: u64) -> Self;
}
#[inline]
pub fn cast<T: Element, U: Element>(x: T) -> U {
U::from_value(x.to_value())
}
macro_rules! impl_int {
($($t:ty => $d:ident, $v:ident;)*) => {$(
impl sealed::Sealed for $t {}
impl Element for $t {
const DTYPE: DType = DType::$d;
type Real = $t;
#[inline]
fn re(self) -> Self {
self
}
#[inline]
fn im(self) -> Self {
Self::default()
}
#[inline]
fn from_parts(re: Self, _: Self) -> Self {
re
}
#[inline]
fn to_value(self) -> Value {
Value::$v(self as _)
}
#[inline]
fn from_value(v: Value) -> Self {
match v {
Value::Bool(b) => b as $t,
Value::Int(i) => i as $t,
Value::UInt(u) => u as $t,
Value::Float(f) | Value::Complex(f, _) => f as $t,
}
}
fn write_bytes(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.to_ne_bytes());
}
fn read_bytes(bytes: &[u8]) -> Self {
<$t>::from_ne_bytes(bytes.try_into().expect("element size"))
}
#[inline]
fn to_bits(self) -> u64 {
(self as u64) & (u64::MAX >> (64 - <$t>::BITS))
}
#[inline]
fn from_bits(bits: u64) -> Self {
bits as $t
}
}
)*};
}
impl_int! {
i8 => I8, Int;
i16 => I16, Int;
i32 => I32, Int;
i64 => I64, Int;
u8 => U8, UInt;
u16 => U16, UInt;
u32 => U32, UInt;
u64 => U64, UInt;
}
impl sealed::Sealed for bool {}
impl Element for bool {
const DTYPE: DType = DType::Bool;
type Real = bool;
#[inline]
fn re(self) -> Self {
self
}
#[inline]
fn im(self) -> Self {
Self::default()
}
#[inline]
fn from_parts(re: Self, _: Self) -> Self {
re
}
#[inline]
fn to_value(self) -> Value {
Value::Bool(self)
}
#[inline]
fn from_value(v: Value) -> Self {
match v {
Value::Bool(b) => b,
Value::Int(i) => i != 0,
Value::UInt(u) => u != 0,
Value::Float(f) | Value::Complex(f, _) => f != 0.0,
}
}
fn write_bytes(self, out: &mut Vec<u8>) {
out.push(u8::from(self));
}
fn read_bytes(bytes: &[u8]) -> Self {
bytes[0] != 0
}
#[inline]
fn to_bits(self) -> u64 {
u64::from(self)
}
#[inline]
fn from_bits(bits: u64) -> Self {
bits & 1 != 0
}
}
impl sealed::Sealed for f64 {}
impl Element for f64 {
const DTYPE: DType = DType::F64;
type Real = f64;
#[inline]
fn re(self) -> Self {
self
}
#[inline]
fn im(self) -> Self {
Self::default()
}
#[inline]
fn from_parts(re: Self, _: Self) -> Self {
re
}
#[inline]
fn to_value(self) -> Value {
Value::Float(self)
}
#[inline]
fn from_value(v: Value) -> Self {
match v {
Value::Bool(b) => f64::from(u8::from(b)),
Value::Int(i) => i as f64,
Value::UInt(u) => u as f64,
Value::Float(f) | Value::Complex(f, _) => f,
}
}
fn write_bytes(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.to_ne_bytes());
}
fn read_bytes(bytes: &[u8]) -> Self {
f64::from_ne_bytes(bytes.try_into().expect("element size"))
}
#[inline]
fn to_bits(self) -> u64 {
f64::to_bits(self)
}
#[inline]
fn from_bits(bits: u64) -> Self {
f64::from_bits(bits)
}
}
impl sealed::Sealed for f32 {}
impl Element for f32 {
const DTYPE: DType = DType::F32;
type Real = f32;
#[inline]
fn re(self) -> Self {
self
}
#[inline]
fn im(self) -> Self {
Self::default()
}
#[inline]
fn from_parts(re: Self, _: Self) -> Self {
re
}
#[inline]
fn to_value(self) -> Value {
Value::Float(f64::from(self))
}
#[inline]
fn from_value(v: Value) -> Self {
match v {
Value::Bool(b) => f32::from(u8::from(b)),
Value::Int(i) => i as f32,
Value::UInt(u) => u as f32,
Value::Float(f) | Value::Complex(f, _) => f as f32,
}
}
fn write_bytes(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.to_ne_bytes());
}
fn read_bytes(bytes: &[u8]) -> Self {
f32::from_ne_bytes(bytes.try_into().expect("element size"))
}
#[inline]
fn to_bits(self) -> u64 {
u64::from(f32::to_bits(self))
}
#[inline]
fn from_bits(bits: u64) -> Self {
f32::from_bits(bits as u32)
}
}
macro_rules! impl_half {
($($t:ty => $d:ident;)*) => {$(
impl sealed::Sealed for $t {}
impl Element for $t {
const DTYPE: DType = DType::$d;
type Real = $t;
#[inline]
fn re(self) -> Self {
self
}
#[inline]
fn im(self) -> Self {
Self::default()
}
#[inline]
fn from_parts(re: Self, _: Self) -> Self {
re
}
#[inline]
fn to_value(self) -> Value {
Value::Float(self.to_f64())
}
#[inline]
fn from_value(v: Value) -> Self {
<$t>::from_f32(f32::from_value(v))
}
fn write_bytes(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.to_ne_bytes());
}
fn read_bytes(bytes: &[u8]) -> Self {
<$t>::from_ne_bytes(bytes.try_into().expect("element size"))
}
#[inline]
fn to_bits(self) -> u64 {
u64::from(<$t>::to_bits(self))
}
#[inline]
fn from_bits(bits: u64) -> Self {
<$t>::from_bits(bits as u16)
}
}
)*};
}
impl_half! {
f16 => F16;
bf16 => BF16;
}
macro_rules! impl_complex {
($($t:ty => $d:ident, $f:ty, $bits:ty;)*) => {$(
impl sealed::Sealed for $t {}
impl Element for $t {
const DTYPE: DType = DType::$d;
type Real = $f;
#[inline]
fn re(self) -> $f {
self.re
}
#[inline]
fn im(self) -> $f {
self.im
}
#[inline]
fn from_parts(re: $f, im: $f) -> Self {
Self::new(re, im)
}
#[inline]
fn to_value(self) -> Value {
Value::Complex(f64::from(self.re), f64::from(self.im))
}
#[inline]
fn from_value(v: Value) -> Self {
match v {
Value::Complex(re, im) => Self::new(re as $f, im as $f),
v => Self::new(<$f>::from_value(v), 0.0),
}
}
fn write_bytes(self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.re.to_ne_bytes());
out.extend_from_slice(&self.im.to_ne_bytes());
}
fn read_bytes(bytes: &[u8]) -> Self {
let (re, im) = bytes.split_at(bytes.len() / 2);
Self::new(
<$f>::from_ne_bytes(re.try_into().expect("element size")),
<$f>::from_ne_bytes(im.try_into().expect("element size")),
)
}
#[inline]
fn to_bits(self) -> u64 {
assert!(
std::mem::size_of::<$bits>() <= 4,
"{} has more than 64 bits",
Self::DTYPE
);
(self.re.to_bits() as u64) | ((self.im.to_bits() as u64) << 32)
}
#[inline]
fn from_bits(bits: u64) -> Self {
assert!(
std::mem::size_of::<$bits>() <= 4,
"{} has more than 64 bits",
Self::DTYPE
);
Self::new(<$f>::from_bits(bits as $bits), <$f>::from_bits((bits >> 32) as $bits))
}
}
)*};
}
impl_complex! {
c64 => C64, f32, u32;
c128 => C128, f64, u64;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn conversions_follow_xla() {
assert_eq!(cast::<f32, i32>(f32::NAN), 0);
assert_eq!(cast::<f32, i32>(1e10), i32::MAX);
assert_eq!(cast::<f32, u8>(-3.5), 0);
assert_eq!(cast::<i32, u8>(-2), 254);
assert!(cast::<f32, bool>(f32::NAN));
assert_eq!(cast::<bool, f32>(true), 1.0);
let x = (1i64 << 60) + (1 << 36) + 1;
assert_eq!(cast::<i64, f32>(x), ((1i64 << 60) + (1 << 37)) as f32);
let y = (1u64 << 60) + (1 << 52) + 1;
assert_eq!(cast::<u64, bf16>(y), bf16::from_f32((1u64 << 60) as f32));
}
#[test]
fn bits_round_trip() {
assert_eq!((-1i8).to_bits(), 0xFF);
assert_eq!(i8::from_bits(0xFF), -1);
assert_eq!(f32::from_bits(1.5f32.to_bits()), 1.5);
assert_eq!(bf16::from_bits(bf16::ONE.to_bits()), bf16::ONE);
assert_eq!(<u16 as Element>::to_bits(0xABCD), 0xABCD);
}
#[test]
fn names_round_trip() {
for d in DType::ALL {
assert_eq!(DType::from_name(d.name()), Some(d));
}
}
}