Skip to main content

ferray_core/array/
view.rs

1// ferray-core: Immutable array view — ArrayView<'a, T, D> (REQ-3)
2
3use ndarray::ShapeBuilder;
4
5use crate::dimension::Dimension;
6use crate::dtype::Element;
7use crate::layout::MemoryLayout;
8
9use super::ArrayFlags;
10use super::owned::Array;
11
12/// An immutable, borrowed view into an existing array's data.
13///
14/// This is a zero-copy slice — no data is cloned. The lifetime `'a`
15/// ties this view to the source array.
16pub struct ArrayView<'a, T: Element, D: Dimension> {
17    pub(crate) inner: ndarray::ArrayView<'a, T, D::NdarrayDim>,
18    pub(crate) dim: D,
19}
20
21impl<'a, T: Element, D: Dimension> ArrayView<'a, T, D> {
22    /// Create from an ndarray view. Crate-internal.
23    pub(crate) fn from_ndarray(inner: ndarray::ArrayView<'a, T, D::NdarrayDim>) -> Self {
24        let dim = D::from_ndarray_dim(&inner.raw_dim());
25        Self { inner, dim }
26    }
27
28    /// Shape as a slice.
29    #[inline]
30    pub fn shape(&self) -> &[usize] {
31        self.inner.shape()
32    }
33
34    /// Number of dimensions.
35    #[inline]
36    pub fn ndim(&self) -> usize {
37        self.dim.ndim()
38    }
39
40    /// Total number of elements.
41    #[inline]
42    pub fn size(&self) -> usize {
43        self.inner.len()
44    }
45
46    /// Whether the view has zero elements.
47    #[inline]
48    pub fn is_empty(&self) -> bool {
49        self.inner.is_empty()
50    }
51
52    /// Strides as a slice.
53    #[inline]
54    pub fn strides(&self) -> &[isize] {
55        self.inner.strides()
56    }
57
58    /// Raw pointer to the first element.
59    #[inline]
60    pub fn as_ptr(&self) -> *const T {
61        self.inner.as_ptr()
62    }
63
64    /// Try to get a contiguous slice.
65    pub fn as_slice(&self) -> Option<&[T]> {
66        self.inner.as_slice()
67    }
68
69    /// Memory layout.
70    pub fn layout(&self) -> MemoryLayout {
71        crate::layout::classify_layout(
72            self.inner.is_standard_layout(),
73            self.dim.as_slice(),
74            self.inner.strides(),
75        )
76    }
77
78    /// Return a reference to the internal dimension descriptor.
79    #[inline]
80    pub fn dim(&self) -> &D {
81        &self.dim
82    }
83
84    /// Convert this view into an owned array by cloning all elements.
85    pub fn to_owned(&self) -> Array<T, D> {
86        Array::from_ndarray(self.inner.to_owned())
87    }
88
89    /// Convert to a flat `Vec<T>` in logical (row-major) order.
90    ///
91    /// Unlike `as_slice()` which requires contiguous memory, this works on
92    /// strided/non-contiguous views by iterating elements in logical order.
93    pub fn to_vec_flat(&self) -> Vec<T> {
94        self.inner.iter().cloned().collect()
95    }
96
97    /// Array flags for this view.
98    pub fn flags(&self) -> ArrayFlags {
99        let layout = self.layout();
100        ArrayFlags {
101            c_contiguous: layout.is_c_contiguous(),
102            f_contiguous: layout.is_f_contiguous(),
103            owndata: false,
104            writeable: false,
105        }
106    }
107}
108
109use crate::dimension::IxDyn;
110
111impl<'a, T: Element> ArrayView<'a, T, IxDyn> {
112    /// Construct a dynamic-rank view from a raw pointer, shape, and strides.
113    ///
114    /// This is the primary escape hatch for crates that need to build views
115    /// with custom stride patterns (e.g., `ferray-stride-tricks`).
116    ///
117    /// # Safety
118    ///
119    /// The caller must ensure:
120    /// - `ptr` is valid for reads for the entire region described by `shape`
121    ///   and `strides`.
122    /// - The lifetime `'a` does not outlive the allocation that `ptr` points
123    ///   into.
124    /// - No mutable reference to the same memory region exists for the
125    ///   duration of `'a`.
126    /// - `strides` are given in units of elements (not bytes).
127    pub unsafe fn from_shape_ptr(ptr: *const T, shape: &[usize], strides: &[usize]) -> Self {
128        let nd_shape = ndarray::IxDyn(shape);
129        let nd_strides = ndarray::IxDyn(strides);
130        let nd_view =
131            unsafe { ndarray::ArrayView::from_shape_ptr(nd_shape.strides(nd_strides), ptr) };
132        Self::from_ndarray(nd_view)
133    }
134}
135
136impl<T: Element, D: Dimension> Clone for ArrayView<'_, T, D> {
137    fn clone(&self) -> Self {
138        Self {
139            inner: self.inner.clone(),
140            dim: self.dim.clone(),
141        }
142    }
143}
144
145// Create an ArrayView from an owned Array
146impl<T: Element, D: Dimension> Array<T, D> {
147    /// Create an immutable view of this array.
148    pub fn view(&self) -> ArrayView<'_, T, D> {
149        ArrayView::from_ndarray(self.inner.view())
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use crate::dimension::Ix2;
157
158    #[test]
159    fn view_from_owned() {
160        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
161            .unwrap();
162        let v = arr.view();
163        assert_eq!(v.shape(), &[2, 3]);
164        assert_eq!(v.size(), 6);
165        assert!(!v.flags().owndata);
166        assert!(!v.flags().writeable);
167    }
168
169    #[test]
170    fn view_shares_data() {
171        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
172            .unwrap();
173        let v = arr.view();
174        // Same pointer
175        assert_eq!(arr.as_ptr(), v.as_ptr());
176    }
177
178    #[test]
179    fn view_to_owned() {
180        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
181            .unwrap();
182        let v = arr.view();
183        let owned = v.to_owned();
184        assert_eq!(owned.shape(), arr.shape());
185        assert_eq!(owned.as_slice().unwrap(), arr.as_slice().unwrap());
186        // But different allocations
187        assert_ne!(owned.as_ptr(), arr.as_ptr());
188    }
189}