omeinsum/tensor/
view.rs

1//! Tensor view types for borrowing.
2
3use super::Tensor;
4use crate::algebra::Scalar;
5use crate::backend::Backend;
6
7/// A borrowed view into a tensor.
8///
9/// This is useful for passing tensors to functions without ownership transfer.
10pub struct TensorView<'a, T: Scalar, B: Backend> {
11    tensor: &'a Tensor<T, B>,
12}
13
14impl<'a, T: Scalar, B: Backend> TensorView<'a, T, B> {
15    /// Create a view from a tensor reference.
16    pub fn new(tensor: &'a Tensor<T, B>) -> Self {
17        Self { tensor }
18    }
19
20    /// Get the shape.
21    pub fn shape(&self) -> &[usize] {
22        self.tensor.shape()
23    }
24
25    /// Get the strides.
26    pub fn strides(&self) -> &[usize] {
27        self.tensor.strides()
28    }
29
30    /// Get number of dimensions.
31    pub fn ndim(&self) -> usize {
32        self.tensor.ndim()
33    }
34
35    /// Get total number of elements.
36    pub fn numel(&self) -> usize {
37        self.tensor.numel()
38    }
39
40    /// Check if contiguous.
41    pub fn is_contiguous(&self) -> bool {
42        self.tensor.is_contiguous()
43    }
44
45    /// Get the underlying tensor.
46    pub fn as_tensor(&self) -> &Tensor<T, B> {
47        self.tensor
48    }
49}
50
51impl<'a, T: Scalar, B: Backend> From<&'a Tensor<T, B>> for TensorView<'a, T, B> {
52    fn from(tensor: &'a Tensor<T, B>) -> Self {
53        Self::new(tensor)
54    }
55}