use crate::fixed_point::FixedPoint;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tensor {
data: Vec<FixedPoint>,
rows: usize,
cols: usize,
}
impl Tensor {
pub fn new(data: Vec<FixedPoint>, rows: usize, cols: usize) -> Option<Self> {
if data.len() == rows * cols {
Some(Self { data, rows, cols })
} else {
None
}
}
pub fn rows(&self) -> usize {
self.rows
}
pub fn cols(&self) -> usize {
self.cols
}
pub fn get(&self, r: usize, c: usize) -> Option<FixedPoint> {
if r < self.rows && c < self.cols {
Some(self.data[r * self.cols + c])
} else {
None
}
}
pub fn reshape(&mut self, rows: usize, cols: usize) -> bool {
if rows * cols == self.data.len() {
self.rows = rows;
self.cols = cols;
true
} else {
false
}
}
}
#[cfg(test)]
#[cfg(feature = "std")]
mod tests {
use super::*;
fn fp(x: f64) -> FixedPoint {
FixedPoint::quantize(x)
}
#[test]
fn get_in_and_out_of_bounds() {
let t = Tensor::new(vec![fp(1.0), fp(2.0), fp(3.0), fp(4.0)], 2, 2).unwrap();
assert_eq!(t.get(1, 1), Some(fp(4.0)));
assert_eq!(t.get(2, 0), None);
}
#[test]
fn reshape_requires_matching_count() {
let mut t = Tensor::new(vec![fp(1.0); 6], 2, 3).unwrap();
assert!(t.reshape(3, 2));
assert!(!t.reshape(4, 2));
}
}
impl Tensor {
pub fn as_slice(&self) -> &[FixedPoint] {
&self.data
}
}
impl Tensor {
pub fn row(&self, r: usize) -> Option<&[FixedPoint]> {
if r < self.rows {
Some(&self.data[r * self.cols..(r + 1) * self.cols])
} else {
None
}
}
}
#[cfg(test)]
mod tests_row {
use super::*;
#[test]
fn row_returns_each_row() {
let data: Vec<FixedPoint> = (0..6).map(|i| FixedPoint::from_raw(i, 16)).collect();
let t = Tensor::new(data, 3, 2).unwrap();
assert_eq!(t.row(0).unwrap().len(), 2);
assert!(t.row(3).is_none());
}
}