use crate::error::MattenError;
use std::fmt;
pub struct Tensor {
data: Vec<f64>,
shape: Vec<usize>,
}
#[allow(clippy::len_without_is_empty)]
impl Tensor {
#[must_use]
pub fn new(data: Vec<f64>, shape: &[usize]) -> Tensor {
Self::build(data, shape, "new").unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_new(data: Vec<f64>, shape: &[usize]) -> Result<Tensor, MattenError> {
Self::build(data, shape, "try_new")
}
fn build(
data: Vec<f64>,
shape: &[usize],
operation: &'static str,
) -> Result<Tensor, MattenError> {
let expected = checked_product(shape, operation)?;
if data.len() != expected {
return Err(MattenError::Shape {
operation,
message: format!(
"data length {} does not match shape {shape:?}, which requires {expected} elements",
data.len()
),
});
}
Ok(Tensor {
data,
shape: shape.to_vec(),
})
}
#[must_use]
pub fn shape(&self) -> &[usize] {
&self.shape
}
#[must_use]
pub fn ndim(&self) -> usize {
self.shape.len()
}
#[must_use]
pub fn len(&self) -> usize {
self.data.len()
}
#[must_use]
pub fn as_slice(&self) -> &[f64] {
&self.data
}
}
impl fmt::Debug for Tensor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const MAX: usize = 8;
write!(f, "Tensor(shape={:?}, data=[", self.shape)?;
for (i, v) in self.data.iter().take(MAX).enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{v:?}")?;
}
if self.data.len() > MAX {
write!(f, ", ... ({} more)", self.data.len() - MAX)?;
}
f.write_str("])")
}
}
fn checked_product(shape: &[usize], operation: &'static str) -> Result<usize, MattenError> {
let mut acc: usize = 1;
for &dim in shape {
acc = acc.checked_mul(dim).ok_or_else(|| MattenError::Allocation {
requested_elements: usize::MAX,
message: format!("shape {shape:?} overflows usize when computing the element count in {operation}"),
})?;
}
Ok(acc)
}