use crate::complex::{c64, c128};
use crate::dtype::{DType, Element};
use half::{bf16, f16};
#[derive(Clone, PartialEq, Debug)]
pub enum Buffer {
Bool(Vec<bool>),
I8(Vec<i8>),
I16(Vec<i16>),
I32(Vec<i32>),
I64(Vec<i64>),
U8(Vec<u8>),
U16(Vec<u16>),
U32(Vec<u32>),
U64(Vec<u64>),
F16(Vec<f16>),
BF16(Vec<bf16>),
F32(Vec<f32>),
F64(Vec<f64>),
C64(Vec<c64>),
C128(Vec<c128>),
}
#[macro_export]
macro_rules! with_buffer {
($buf:expr, |$v:ident| $body:expr) => {
match $buf {
$crate::Buffer::Bool($v) => $body,
$crate::Buffer::I8($v) => $body,
$crate::Buffer::I16($v) => $body,
$crate::Buffer::I32($v) => $body,
$crate::Buffer::I64($v) => $body,
$crate::Buffer::U8($v) => $body,
$crate::Buffer::U16($v) => $body,
$crate::Buffer::U32($v) => $body,
$crate::Buffer::U64($v) => $body,
$crate::Buffer::F16($v) => $body,
$crate::Buffer::BF16($v) => $body,
$crate::Buffer::F32($v) => $body,
$crate::Buffer::F64($v) => $body,
$crate::Buffer::C64($v) => $body,
$crate::Buffer::C128($v) => $body,
}
};
}
#[macro_export]
macro_rules! with_dtype {
($dtype:expr, |$t:ident| $body:expr) => {
match $dtype {
$crate::DType::Bool => {
type $t = bool;
$body
}
$crate::DType::I8 => {
type $t = i8;
$body
}
$crate::DType::I16 => {
type $t = i16;
$body
}
$crate::DType::I32 => {
type $t = i32;
$body
}
$crate::DType::I64 => {
type $t = i64;
$body
}
$crate::DType::U8 => {
type $t = u8;
$body
}
$crate::DType::U16 => {
type $t = u16;
$body
}
$crate::DType::U32 => {
type $t = u32;
$body
}
$crate::DType::U64 => {
type $t = u64;
$body
}
$crate::DType::F16 => {
type $t = $crate::f16;
$body
}
$crate::DType::BF16 => {
type $t = $crate::bf16;
$body
}
$crate::DType::F32 => {
type $t = f32;
$body
}
$crate::DType::F64 => {
type $t = f64;
$body
}
$crate::DType::C64 => {
type $t = $crate::c64;
$body
}
$crate::DType::C128 => {
type $t = $crate::c128;
$body
}
}
};
}
impl Buffer {
pub fn dtype(&self) -> DType {
with_buffer!(self, |v| element_dtype(v))
}
pub fn len(&self) -> usize {
with_buffer!(self, |v| v.len())
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn convert(&self, dtype: DType) -> Buffer {
with_buffer!(self, |v| with_dtype!(dtype, |U| Buffer::from_vec(
v.iter()
.map(|&x| crate::cast::<_, U>(x))
.collect::<Vec<U>>()
)))
}
pub fn from_vec<T: Element>(v: Vec<T>) -> Buffer {
T::wrap(v)
}
pub fn as_slice<T: Element>(&self) -> Option<&[T]> {
T::view(self)
}
}
fn element_dtype<T: Element>(_: &[T]) -> DType {
T::DTYPE
}
pub trait BufferElement: Sized {
fn wrap(v: Vec<Self>) -> Buffer;
fn view(b: &Buffer) -> Option<&[Self]>;
}
macro_rules! impl_buffer_element {
($($t:ty => $v:ident;)*) => {$(
impl BufferElement for $t {
fn wrap(v: Vec<Self>) -> Buffer {
Buffer::$v(v)
}
fn view(b: &Buffer) -> Option<&[Self]> {
match b {
Buffer::$v(v) => Some(v),
_ => None,
}
}
}
)*};
}
impl_buffer_element! {
bool => Bool; i8 => I8; i16 => I16; i32 => I32; i64 => I64;
u8 => U8; u16 => U16; u32 => U32; u64 => U64;
f16 => F16; bf16 => BF16; f32 => F32; f64 => F64; c64 => C64; c128 => C128;
}