use core::ops::{Deref, DerefMut};
use crate::buffer::BufferStats;
use crate::math::Scalar;
pub trait Buffer<T: Scalar> {
fn capacity(&self) -> usize;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn is_full(&self) -> bool {
self.len() == self.capacity()
}
fn as_slice(&self) -> &[T];
fn as_mut_slice(&mut self) -> &mut [T];
fn fill(&mut self, value: T);
fn copy_from(&mut self, src: &[T]);
fn clear(&mut self);
fn stats(&self) -> BufferStats {
BufferStats::new()
}
fn reset_stats(&mut self) {}
}
#[derive(Debug, Clone)]
#[repr(align(16))]
pub struct FixedBuffer<T, const SIZE: usize> {
data: [T; SIZE],
}
impl<T: Scalar, const SIZE: usize> FixedBuffer<T, SIZE> {
pub fn new() -> Self {
Self {
data: [T::default(); SIZE],
}
}
pub fn from_array(data: [T; SIZE]) -> Self {
Self { data }
}
pub fn from_slice(slice: &[T]) -> Self {
let mut data = [T::default(); SIZE];
let len = slice.len().min(SIZE);
data[..len].copy_from_slice(&slice[..len]);
Self { data }
}
pub fn as_array(&self) -> &[T; SIZE] {
&self.data
}
pub fn as_mut_array(&mut self) -> &mut [T; SIZE] {
&mut self.data
}
}
impl<T: Scalar, const SIZE: usize> Default for FixedBuffer<T, SIZE> {
fn default() -> Self {
Self::new()
}
}
impl<T: Scalar, const SIZE: usize> Deref for FixedBuffer<T, SIZE> {
type Target = [T; SIZE];
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T: Scalar, const SIZE: usize> DerefMut for FixedBuffer<T, SIZE> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data
}
}
impl<T: Scalar, const SIZE: usize> From<[T; SIZE]> for FixedBuffer<T, SIZE> {
fn from(data: [T; SIZE]) -> Self {
Self::from_array(data)
}
}
impl<T: Scalar, const SIZE: usize> Buffer<T> for FixedBuffer<T, SIZE> {
fn capacity(&self) -> usize {
SIZE
}
fn len(&self) -> usize {
SIZE
}
fn as_slice(&self) -> &[T] {
&self.data
}
fn as_mut_slice(&mut self) -> &mut [T] {
&mut self.data
}
fn fill(&mut self, value: T) {
self.data.fill(value);
}
fn copy_from(&mut self, src: &[T]) {
let len = src.len().min(SIZE);
self.data[..len].copy_from_slice(&src[..len]);
}
fn clear(&mut self) {
self.data.fill(T::default());
}
}
#[derive(Debug, Clone)]
pub struct HeapBuffer<T> {
data: Vec<T>,
}
impl<T: Scalar> HeapBuffer<T> {
pub fn new(size: usize) -> Self {
Self {
data: vec![T::default(); size],
}
}
pub fn from_vec(data: Vec<T>) -> Self {
Self { data }
}
}
impl<T: Scalar> Buffer<T> for HeapBuffer<T> {
fn capacity(&self) -> usize {
self.data.capacity()
}
fn len(&self) -> usize {
self.data.len()
}
fn as_slice(&self) -> &[T] {
&self.data
}
fn as_mut_slice(&mut self) -> &mut [T] {
&mut self.data
}
fn fill(&mut self, value: T) {
self.data.fill(value);
}
fn copy_from(&mut self, src: &[T]) {
let len = src.len().min(self.data.len());
self.data[..len].copy_from_slice(&src[..len]);
}
fn clear(&mut self) {
self.data.clear();
}
}