Skip to main content

rusanta_core/memory/
buffer.rs

1use std::ops::{Index, IndexMut};
2use crate::traits::numeric::Numeric;
3
4/// Contiguous, heap-allocated buffer for storing raw numerical data.
5///
6/// `Buffer<T>` is the fundamental storage engine used across Rusanta constructs
7/// like NdArray, Tensor, and Series.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Buffer<T> {
10    data: Vec<T>,
11}
12
13impl<T: Numeric> Buffer<T> {
14    /// Creates a new `Buffer` with given element values.
15    #[inline]
16    pub fn new(data: Vec<T>) -> Self {
17        Self { data }
18    }
19
20    /// Creates a new `Buffer` of specified size filled with a default value.
21    #[inline]
22    pub fn filled(value: T, len: usize) -> Self {
23        Self {
24            data: vec![value; len],
25        }
26    }
27
28    /// Returns the total number of elements stored in the buffer.
29    #[inline]
30    pub fn len(&self) -> usize {
31        self.data.len()
32    }
33
34    /// Returns `true` if the buffer contains no elements.
35    #[inline]
36    pub fn is_empty(&self) -> bool {
37        self.data.is_empty()
38    }
39
40    /// Provides an immutable reference to the underlying contiguous slice.
41    #[inline]
42    pub fn as_slice(&self) -> &[T] {
43        &self.data
44    }
45
46    /// Provides a mutable reference to the underlying contiguous slice.
47    #[inline]
48    pub fn as_mut_slice(&mut self) -> &mut [T] {
49        &mut self.data
50    }
51
52    /// Converts the buffer into its underlying `Vec<T>`.
53    #[inline]
54    pub fn into_vec(self) -> Vec<T> {
55        self.data
56    }
57}
58
59// ======================================================
60// Standard Trait Implementations
61// ======================================================
62
63impl<T> From<Vec<T>> for Buffer<T> {
64    #[inline]
65    fn from(data: Vec<T>) -> Self {
66        Self { data }
67    }
68}
69
70impl<T> Index<usize> for Buffer<T> {
71    type Output = T;
72
73    #[inline]
74    fn index(&self, idx: usize) -> &Self::Output {
75        &self.data[idx]
76    }
77}
78
79impl<T> IndexMut<usize> for Buffer<T> {
80    #[inline]
81    fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
82        &mut self.data[idx]
83    }
84}