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        if self.inner.is_standard_layout() {
72            MemoryLayout::C
73        } else {
74            let shape = self.dim.as_slice();
75            let strides: Vec<isize> = self.inner.strides().to_vec();
76            crate::layout::detect_layout(shape, &strides)
77        }
78    }
79
80    /// Return a reference to the internal dimension descriptor.
81    #[inline]
82    pub fn dim(&self) -> &D {
83        &self.dim
84    }
85
86    /// Convert this view into an owned array by cloning all elements.
87    pub fn to_owned(&self) -> Array<T, D> {
88        Array::from_ndarray(self.inner.to_owned())
89    }
90
91    /// Array flags for this view.
92    pub fn flags(&self) -> ArrayFlags {
93        let layout = self.layout();
94        ArrayFlags {
95            c_contiguous: layout.is_c_contiguous(),
96            f_contiguous: layout.is_f_contiguous(),
97            owndata: false,
98            writeable: false,
99        }
100    }
101}
102
103use crate::dimension::IxDyn;
104
105impl<'a, T: Element> ArrayView<'a, T, IxDyn> {
106    /// Construct a dynamic-rank view from a raw pointer, shape, and strides.
107    ///
108    /// This is the primary escape hatch for crates that need to build views
109    /// with custom stride patterns (e.g., `ferray-stride-tricks`).
110    ///
111    /// # Safety
112    ///
113    /// The caller must ensure:
114    /// - `ptr` is valid for reads for the entire region described by `shape`
115    ///   and `strides`.
116    /// - The lifetime `'a` does not outlive the allocation that `ptr` points
117    ///   into.
118    /// - No mutable reference to the same memory region exists for the
119    ///   duration of `'a`.
120    /// - `strides` are given in units of elements (not bytes).
121    pub unsafe fn from_shape_ptr(ptr: *const T, shape: &[usize], strides: &[usize]) -> Self {
122        let nd_shape = ndarray::IxDyn(shape);
123        let nd_strides = ndarray::IxDyn(strides);
124        let nd_view =
125            unsafe { ndarray::ArrayView::from_shape_ptr(nd_shape.strides(nd_strides), ptr) };
126        Self::from_ndarray(nd_view)
127    }
128}
129
130impl<T: Element, D: Dimension> Clone for ArrayView<'_, T, D> {
131    fn clone(&self) -> Self {
132        Self {
133            inner: self.inner.clone(),
134            dim: self.dim.clone(),
135        }
136    }
137}
138
139// Create an ArrayView from an owned Array
140impl<T: Element, D: Dimension> Array<T, D> {
141    /// Create an immutable view of this array.
142    pub fn view(&self) -> ArrayView<'_, T, D> {
143        ArrayView::from_ndarray(self.inner.view())
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::dimension::Ix2;
151
152    #[test]
153    fn view_from_owned() {
154        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
155            .unwrap();
156        let v = arr.view();
157        assert_eq!(v.shape(), &[2, 3]);
158        assert_eq!(v.size(), 6);
159        assert!(!v.flags().owndata);
160        assert!(!v.flags().writeable);
161    }
162
163    #[test]
164    fn view_shares_data() {
165        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
166            .unwrap();
167        let v = arr.view();
168        // Same pointer
169        assert_eq!(arr.as_ptr(), v.as_ptr());
170    }
171
172    #[test]
173    fn view_to_owned() {
174        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
175            .unwrap();
176        let v = arr.view();
177        let owned = v.to_owned();
178        assert_eq!(owned.shape(), arr.shape());
179        assert_eq!(owned.as_slice().unwrap(), arr.as_slice().unwrap());
180        // But different allocations
181        assert_ne!(owned.as_ptr(), arr.as_ptr());
182    }
183}