Skip to main content

strided_view/
view.rs

1//! Julia-like dynamic-rank strided view types.
2//!
3//! This module provides the canonical view types for strided operations,
4//! matching Julia's StridedViews.jl data model:
5//!
6//! - [`StridedView`]: Immutable dynamic-rank strided view with lazy element operations
7//! - [`StridedViewMut`]: Mutable dynamic-rank strided view (Identity op only)
8//! - [`StridedArray`]: Owned strided multidimensional array
9//!
10//! A view's shape and strides are a small inline-or-heap container with
11//! capacity [`crate::INLINE_RANK`]: every constructor, clone, and metadata
12//! transform allocates nothing up to that rank and spills gracefully above
13//! it. The view itself only borrows the element data.
14//!
15//! The metadata container is `tinyvec::ArrayVec`, unified across tensor4all
16//! repositories (tensor4all-agent-rules#22, strided-rs#312). `ArrayVec` is
17//! `Copy` for `Copy` items, so a clone is one fixed-size bitwise copy, and the
18//! heap fallback for rank above [`INLINE_RANK`] lives in a separate
19//! `Option<Box<SpilledMeta>>` so the inline value has no drop glue.
20
21use std::marker::PhantomData;
22use std::mem::MaybeUninit;
23use std::ops::{Index, IndexMut};
24
25use tinyvec::ArrayVec;
26
27use crate::element_op::{ComposableElementOp, ElementOp, ElementOpApply, Identity};
28use crate::{AxisVec, Result, StrideVec, StridedError, INLINE_RANK};
29
30/// Build an `ArrayVec` from at most [`INLINE_RANK`] elements.
31///
32/// The value is written with literal-count arms: a runtime-length
33/// `copy_from_slice` or loop is recognized by LLVM and lowered to a `memcpy`
34/// PLT call, whose overhead dominates a handful of words.
35#[inline(always)]
36fn arrayvec_from_slice<T: Copy + Default>(src: &[T]) -> ArrayVec<[T; INLINE_RANK]> {
37    debug_assert!(src.len() <= INLINE_RANK);
38    let n = src.len();
39    let mut buf = [T::default(); INLINE_RANK];
40    match n {
41        0 => {}
42        1 => buf[0] = src[0],
43        2 => {
44            buf[0] = src[0];
45            buf[1] = src[1];
46        }
47        3 => {
48            buf[0] = src[0];
49            buf[1] = src[1];
50            buf[2] = src[2];
51        }
52        4 => {
53            buf[0] = src[0];
54            buf[1] = src[1];
55            buf[2] = src[2];
56            buf[3] = src[3];
57        }
58        5 => {
59            buf[0] = src[0];
60            buf[1] = src[1];
61            buf[2] = src[2];
62            buf[3] = src[3];
63            buf[4] = src[4];
64        }
65        6 => {
66            buf[0] = src[0];
67            buf[1] = src[1];
68            buf[2] = src[2];
69            buf[3] = src[3];
70            buf[4] = src[4];
71            buf[5] = src[5];
72        }
73        7 => {
74            buf[0] = src[0];
75            buf[1] = src[1];
76            buf[2] = src[2];
77            buf[3] = src[3];
78            buf[4] = src[4];
79            buf[5] = src[5];
80            buf[6] = src[6];
81        }
82        _ => {
83            buf[0] = src[0];
84            buf[1] = src[1];
85            buf[2] = src[2];
86            buf[3] = src[3];
87            buf[4] = src[4];
88            buf[5] = src[5];
89            buf[6] = src[6];
90            buf[7] = src[7];
91        }
92    }
93    ArrayVec::from_array_len(buf, n)
94}
95
96/// Heap-owned metadata used only above [`INLINE_RANK`].
97#[derive(Clone, Debug)]
98struct SpilledMeta {
99    dims: Box<[usize]>,
100    strides: Box<[isize]>,
101}
102
103/// Shape and strides of a view or array.
104///
105/// Rank `<= INLINE_RANK` is stored inline in two `ArrayVec`s and the
106/// `spilled` slot is `None`, so cloning the whole metadata is a fixed-size
107/// bitwise copy with one predictable `None` check. A higher rank keeps the
108/// inline buffers empty and boxes both vectors.
109#[derive(Debug)]
110struct ViewMeta {
111    inline_dims: ArrayVec<[usize; INLINE_RANK]>,
112    inline_strides: ArrayVec<[isize; INLINE_RANK]>,
113    spilled: Option<Box<SpilledMeta>>,
114}
115
116impl Clone for ViewMeta {
117    #[inline]
118    fn clone(&self) -> Self {
119        Self {
120            inline_dims: self.inline_dims,
121            inline_strides: self.inline_strides,
122            spilled: self.spilled.clone(),
123        }
124    }
125}
126
127impl ViewMeta {
128    #[inline(always)]
129    fn from_slices(dims: &[usize], strides: &[isize]) -> Self {
130        debug_assert_eq!(dims.len(), strides.len());
131        if dims.len() <= INLINE_RANK {
132            Self {
133                inline_dims: arrayvec_from_slice(dims),
134                inline_strides: arrayvec_from_slice(strides),
135                spilled: None,
136            }
137        } else {
138            Self {
139                inline_dims: ArrayVec::new(),
140                inline_strides: ArrayVec::new(),
141                spilled: Some(Box::new(SpilledMeta {
142                    dims: dims.into(),
143                    strides: strides.into(),
144                })),
145            }
146        }
147    }
148
149    #[inline]
150    fn dims(&self) -> &[usize] {
151        match &self.spilled {
152            Some(spilled) => &spilled.dims,
153            None => self.inline_dims.as_slice(),
154        }
155    }
156
157    #[inline]
158    fn strides(&self) -> &[isize] {
159        match &self.spilled {
160            Some(spilled) => &spilled.strides,
161            None => self.inline_strides.as_slice(),
162        }
163    }
164}
165
166#[inline]
167fn empty_layout(dims: &[usize]) -> bool {
168    dims.contains(&0)
169}
170
171#[inline]
172fn empty_const_ptr<T>() -> *const T {
173    core::ptr::NonNull::<T>::dangling().as_ptr()
174}
175
176#[inline]
177fn empty_mut_ptr<T>() -> *mut T {
178    core::ptr::NonNull::<T>::dangling().as_ptr()
179}
180
181// ============================================================================
182// Validation helpers
183// ============================================================================
184
185/// Validate that all accessed offsets stay within `[0, len)`.
186#[inline]
187pub(crate) fn validate_bounds(
188    len: usize,
189    dims: &[usize],
190    strides: &[isize],
191    offset: isize,
192) -> Result<()> {
193    if dims.len() != strides.len() {
194        return Err(StridedError::StrideLengthMismatch);
195    }
196    // Empty array - no access needed
197    if dims.contains(&0) {
198        return Ok(());
199    }
200    // Compute min and max offsets
201    let mut min_offset = offset;
202    let mut max_offset = offset;
203    for (&dim, &stride) in dims.iter().zip(strides.iter()) {
204        if dim > 1 {
205            let last = dim
206                .checked_sub(1)
207                .and_then(|value| isize::try_from(value).ok())
208                .ok_or(StridedError::OffsetOverflow)?;
209            let end = stride
210                .checked_mul(last)
211                .ok_or(StridedError::OffsetOverflow)?;
212            if end >= 0 {
213                max_offset = max_offset
214                    .checked_add(end)
215                    .ok_or(StridedError::OffsetOverflow)?;
216            } else {
217                min_offset = min_offset
218                    .checked_add(end)
219                    .ok_or(StridedError::OffsetOverflow)?;
220            }
221        }
222    }
223    if min_offset < 0 || max_offset < 0 {
224        return Err(StridedError::OffsetOverflow);
225    }
226    if max_offset as usize >= len {
227        return Err(StridedError::OffsetOverflow);
228    }
229    Ok(())
230}
231
232/// Offset of `indices` inside `dims`/`strides`, relative to `base`.
233///
234/// # Panics
235///
236/// Panics when `indices` is not the full index for `dims`, an index is out of
237/// bounds, or an indexed offset does not fit `isize`. Every panicking element
238/// accessor below reports those conditions through this helper.
239#[inline]
240fn indexed_offset(dims: &[usize], strides: &[isize], indices: &[usize], base: isize) -> isize {
241    assert_eq!(indices.len(), dims.len(), "wrong number of indices");
242    let mut offset = base;
243    for (i, &index) in indices.iter().enumerate() {
244        assert!(
245            index < dims[i],
246            "index {} out of bounds for dim {}",
247            index,
248            dims[i]
249        );
250        offset = isize::try_from(index)
251            .ok()
252            .and_then(|index| index.checked_mul(strides[i]))
253            .and_then(|step| offset.checked_add(step))
254            .expect("index offset overflow");
255    }
256    offset
257}
258
259/// Number of elements of `dims`: the checked product of the extents.
260///
261/// A zero extent wins before the product, so a zero-sized shape is empty even
262/// when its other extents would overflow. Returns
263/// [`StridedError::OffsetOverflow`] when the product does not fit `usize`
264/// (tensor4all/strided-rs#205).
265#[inline]
266fn checked_element_count(dims: &[usize]) -> Result<usize> {
267    if dims.contains(&0) {
268        return Ok(0);
269    }
270    dims.iter()
271        .try_fold(1usize, |acc, &dim| acc.checked_mul(dim))
272        .ok_or(StridedError::OffsetOverflow)
273}
274
275/// [`checked_element_count`] for the infallible `len` accessors.
276///
277/// # Panics
278///
279/// Panics when the element count does not fit `usize`, which only a
280/// broadcast (stride-0) layout can reach.
281#[inline]
282fn element_count(dims: &[usize]) -> usize {
283    checked_element_count(dims).expect("element count overflows usize")
284}
285
286/// Dense strides of `dims` with the axes visited fastest first in `order`.
287///
288/// Each stride is the product of the extents of the faster axes and must fit
289/// `isize`; otherwise [`StridedError::OffsetOverflow`]. A zero-sized shape is
290/// never dereferenced, so its strides saturate instead of failing: an empty
291/// array with huge extents stays constructible.
292fn checked_dense_strides(dims: &[usize], order: impl Iterator<Item = usize>) -> Result<StrideVec> {
293    let empty = dims.contains(&0);
294    let mut strides = StrideVec::new();
295    strides.resize(dims.len(), 0isize);
296    let mut step = 1isize;
297    for axis in order {
298        strides[axis] = step;
299        let dim = isize::try_from(dims[axis]).ok();
300        step = match dim.and_then(|dim| step.checked_mul(dim)) {
301            Some(next) => next,
302            None if empty => isize::MAX,
303            // The last axis's step is never stored, but it is the element
304            // count, which must also fit for the allocation and the offsets.
305            None => return Err(StridedError::OffsetOverflow),
306        };
307    }
308    Ok(strides)
309}
310
311fn checked_col_major_strides(dims: &[usize]) -> Result<StrideVec> {
312    checked_dense_strides(dims, 0..dims.len())
313}
314
315fn checked_row_major_strides(dims: &[usize]) -> Result<StrideVec> {
316    checked_dense_strides(dims, (0..dims.len()).rev())
317}
318
319/// Compute column-major strides (Julia default: first index varies fastest).
320///
321/// Returns an inline [`StrideVec`]: the result does not allocate at rank
322/// `<= INLINE_RANK` and spills above it.
323///
324/// # Panics
325///
326/// Panics when a stride or the element count of a non-empty shape does not
327/// fit `isize`. A shape with a zero extent never panics.
328///
329/// # Examples
330///
331/// ```
332/// use strided_view::col_major_strides;
333///
334/// // Julia default: first index varies fastest.
335/// assert_eq!(col_major_strides(&[2, 3]).as_slice(), &[1, 2]);
336/// ```
337#[inline]
338pub fn col_major_strides(dims: &[usize]) -> StrideVec {
339    checked_col_major_strides(dims).expect("column-major strides overflow isize")
340}
341
342/// Compute row-major strides (C default: last index varies fastest).
343///
344/// Returns an inline [`StrideVec`]: the result does not allocate at rank
345/// `<= INLINE_RANK` and spills above it.
346///
347/// # Panics
348///
349/// Panics when a stride or the element count of a non-empty shape does not
350/// fit `isize`. A shape with a zero extent never panics.
351///
352/// # Examples
353///
354/// ```
355/// use strided_view::row_major_strides;
356///
357/// // C default: last index varies fastest.
358/// assert_eq!(row_major_strides(&[2, 3]).as_slice(), &[3, 1]);
359/// ```
360#[inline]
361pub fn row_major_strides(dims: &[usize]) -> StrideVec {
362    checked_row_major_strides(dims).expect("row-major strides overflow isize")
363}
364
365// ============================================================================
366// StridedView
367// ============================================================================
368
369/// Dynamic-rank immutable strided view with lazy element operations.
370///
371/// This is the Julia-equivalent `StridedView` type with:
372/// - Dynamic rank, with metadata stored inline for up to [`INLINE_RANK`]
373///   dimensions ([`StridedView::new`] copies the caller's layout, so the view
374///   borrows only the element data)
375/// - Lazy element operations via the `Op` type parameter
376/// - Zero-copy transformations (permute, transpose, adjoint, conj)
377///
378/// # Type Parameters
379/// - `'a`: Lifetime of the underlying data
380/// - `T`: Element type
381/// - `Op`: Element operation applied lazily on access (default: `Identity`)
382///
383/// # Size
384///
385/// The inline metadata makes the view 184 bytes on 64-bit targets for
386/// `usize`/`isize` strides.
387///
388/// # Auto traits
389///
390/// The view borrows its elements, so it is `Send` only when `T: Sync` (a
391/// shared slice is). A view of non-`Sync` data is not `Send`:
392///
393/// ```compile_fail
394/// use std::cell::Cell;
395/// use strided_view::StridedView;
396///
397/// fn assert_send<T: Send>() {}
398/// assert_send::<StridedView<'static, Cell<i32>>>();
399/// ```
400pub struct StridedView<'a, T, Op = Identity> {
401    ptr: *const T,
402    data: &'a [T],
403    meta: ViewMeta,
404    offset: isize,
405    _op: PhantomData<Op>,
406}
407
408// SAFETY: `StridedView` owns no `T`. It holds `&'a [T]` and a `*const T`
409// derived from it, so moving the view moves a shared borrow, which is `Send`
410// exactly when `T: Sync`. `Op` appears only in `PhantomData`, and `ViewMeta` is
411// owned metadata (an inline `tinyvec::ArrayVec` plus an optional box).
412unsafe impl<T: Sync, Op: Send> Send for StridedView<'_, T, Op> {}
413// SAFETY: a shared `&StridedView` hands out only `&T` (`get`, `ptr`, the
414// `ElementOp` read path) and never `&mut T`, so sharing is sound when `T: Sync`.
415// `Op` is `Sync` and appears only in `PhantomData`.
416unsafe impl<T: Sync, Op: Sync> Sync for StridedView<'_, T, Op> {}
417
418impl<T, Op> Clone for StridedView<'_, T, Op> {
419    #[inline]
420    fn clone(&self) -> Self {
421        Self {
422            ptr: self.ptr,
423            data: self.data,
424            meta: self.meta.clone(),
425            offset: self.offset,
426            _op: PhantomData,
427        }
428    }
429}
430
431impl<T: std::fmt::Debug, Op> std::fmt::Debug for StridedView<'_, T, Op> {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.debug_struct("StridedView")
434            .field("dims", &self.meta.dims())
435            .field("strides", &self.meta.strides())
436            .field("offset", &self.offset)
437            .finish()
438    }
439}
440
441/// The cached base pointer of a view over `data` at `offset`.
442///
443/// An empty layout gets the dangling pointer rather than `data + offset`: a
444/// zero-sized extent may sit at an offset no element of `data` reaches.
445#[inline]
446fn base_ptr<T>(data: &[T], dims: &[usize], offset: isize) -> *const T {
447    if empty_layout(dims) {
448        empty_const_ptr()
449    } else {
450        // SAFETY: every caller reaches `base_ptr` from `from_meta`, whose
451        // `dims`/`strides`/`offset` were either accepted by `validate_bounds`
452        // (view.rs:187) — `StridedView::new`, `StridedViewMut::new`, the
453        // re-validated diagonal path, or a metadata transform that only reorders
454        // axes or zeroes strides and therefore cannot enlarge the reachable
455        // offset set — or were supplied under the `new_unchecked` contract. The
456        // empty-layout branch above excludes the case where `offset` may point
457        // past `data`.
458        unsafe { data.as_ptr().offset(offset) }
459    }
460}
461
462/// A view from already-validated metadata, with the element op chosen here.
463#[inline]
464fn from_meta<'a, T, Op>(
465    data: &'a [T],
466    dims: &[usize],
467    strides: &[isize],
468    offset: isize,
469) -> StridedView<'a, T, Op> {
470    let meta = ViewMeta::from_slices(dims, strides);
471    let ptr = base_ptr(data, meta.dims(), offset);
472    StridedView {
473        ptr,
474        data,
475        meta,
476        offset,
477        _op: PhantomData,
478    }
479}
480
481impl<'a, T, Op> StridedView<'a, T, Op> {
482    /// Create an immutable strided view, copying the caller's metadata inline.
483    ///
484    /// `dims`, `strides`, and `offset` are in units of `T` (elements, not
485    /// bytes).
486    ///
487    /// The layout is copied into the view's inline storage, so it does not
488    /// need to outlive the view and no heap allocation happens at rank
489    /// `<= INLINE_RANK`. The view's lifetime is tied to `data` only.
490    ///
491    /// # Errors
492    ///
493    /// Returns [`StridedError::StrideLengthMismatch`] when `dims` and
494    /// `strides` have different lengths, and
495    /// [`StridedError::OffsetOverflow`] when a reachable offset is not
496    /// representable: `dim - 1` of a non-unit extent does not fit `isize`, a
497    /// stride times that last index or the accumulated offsets overflow
498    /// `isize` or go negative, or the highest reachable offset is not below
499    /// the buffer length. A layout with a zero extent skips this check.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use strided_view::StridedView;
505    ///
506    /// let data = [1.0f64, 2.0, 3.0, 4.0, 5.0, 6.0];
507    /// let view = StridedView::<f64>::new(&data, &[2, 3], &[1, 2], 0).unwrap();
508    /// assert_eq!(view.dims(), &[2, 3]);
509    /// assert_eq!(view.get(&[1, 2]), 6.0);
510    /// ```
511    #[inline]
512    pub fn new(data: &'a [T], dims: &[usize], strides: &[isize], offset: isize) -> Result<Self> {
513        validate_bounds(data.len(), dims, strides, offset)?;
514        Ok(from_meta(data, dims, strides, offset))
515    }
516
517    /// Create a view without bounds checking, copying the caller's metadata.
518    ///
519    /// `dims`, `strides`, and `offset` are in units of `T` (elements, not
520    /// bytes).
521    ///
522    /// # Safety
523    /// The caller must ensure all index combinations stay within bounds.
524    ///
525    /// # Examples
526    ///
527    /// ```
528    /// use strided_view::StridedView;
529    ///
530    /// let data = [1.0f64, 2.0, 3.0, 4.0];
531    /// // SAFETY: the largest reachable offset, 1 * 1 + 1 * 2 = 3, is below
532    /// // `data.len() == 4`.
533    /// let view = unsafe { StridedView::<f64>::new_unchecked(&data, &[2, 2], &[1, 2], 0) };
534    /// assert_eq!(view.ndim(), 2);
535    /// ```
536    #[inline]
537    pub unsafe fn new_unchecked(
538        data: &'a [T],
539        dims: &[usize],
540        strides: &[isize],
541        offset: isize,
542    ) -> Self {
543        from_meta(data, dims, strides, offset)
544    }
545
546    /// Returns the shape (dimension sizes) of this view.
547    #[inline]
548    pub fn dims(&self) -> &[usize] {
549        self.meta.dims()
550    }
551
552    /// Returns the strides (in units of `T`) for each dimension.
553    #[inline]
554    pub fn strides(&self) -> &[isize] {
555        self.meta.strides()
556    }
557
558    /// Returns the offset into the backing data, in units of `T` (elements, not bytes).
559    #[inline]
560    pub fn offset(&self) -> isize {
561        self.offset
562    }
563
564    /// Returns the number of dimensions (rank).
565    #[inline]
566    pub fn ndim(&self) -> usize {
567        self.dims().len()
568    }
569
570    /// Returns the total number of elements.
571    ///
572    /// # Panics
573    ///
574    /// Panics when the element count does not fit `usize`, which only a
575    /// broadcast (stride-0) layout can reach.
576    #[inline]
577    pub fn len(&self) -> usize {
578        element_count(self.dims())
579    }
580
581    /// Returns `true` if any dimension is zero.
582    #[inline]
583    pub fn is_empty(&self) -> bool {
584        self.dims().contains(&0)
585    }
586
587    /// Returns a reference to the backing data slice.
588    #[inline]
589    pub fn data(&self) -> &'a [T] {
590        self.data
591    }
592
593    /// Raw const pointer to element at the view's base offset.
594    #[inline]
595    pub fn ptr(&self) -> *const T {
596        self.ptr
597    }
598
599    /// Permute dimensions.
600    ///
601    /// # Errors
602    ///
603    /// Returns [`StridedError::RankMismatch`] when `perm` does not have one
604    /// entry per axis, and [`StridedError::InvalidAxis`] when an entry
605    /// names an axis outside the rank or repeats an axis.
606    pub fn permute(&self, perm: &[usize]) -> Result<StridedView<'a, T, Op>> {
607        let rank = self.dims().len();
608        if perm.len() != rank {
609            return Err(StridedError::RankMismatch(perm.len(), rank));
610        }
611        let mut seen: tinyvec::TinyVec<[bool; INLINE_RANK]> = tinyvec::TinyVec::new();
612        seen.resize(rank, false);
613        for &p in perm {
614            if p >= rank {
615                return Err(StridedError::InvalidAxis { axis: p, rank });
616            }
617            if seen[p] {
618                return Err(StridedError::InvalidAxis { axis: p, rank });
619            }
620            seen[p] = true;
621        }
622        let new_dims: AxisVec = perm.iter().map(|&p| self.dims()[p]).collect();
623        let new_strides: StrideVec = perm.iter().map(|&p| self.strides()[p]).collect();
624        Ok(from_meta(self.data, &new_dims, &new_strides, self.offset))
625    }
626
627    /// Create a diagonal view by fusing repeated axis pairs via stride trick (zero-copy).
628    ///
629    /// Each pair `(a, b)` ties axes `a` and `b` to one index. Pairs that share
630    /// an axis chain into one class (`[(0, 1), (1, 2)]` and `[(0, 1), (0, 2)]`
631    /// both tie axes 0, 1 and 2), and each class becomes one axis:
632    /// - New stride = the sum of the strides of the axes in the class
633    /// - New dim = the minimum of their dims
634    /// - The class sits at its lowest-numbered axis; the others are removed
635    /// - Pairs use **original** axis numbering; their order does not matter,
636    ///   and repeating a pair has no further effect
637    ///
638    /// # Errors
639    ///
640    /// Returns [`StridedError::InvalidAxis`] when a pair names an axis outside
641    /// the rank or names the same axis twice, and
642    /// [`StridedError::OffsetOverflow`] when a fused stride does not fit
643    /// `isize` or the fused layout reaches past the backing allocation.
644    ///
645    /// # Example
646    /// `A[i,i,j]` shape=`[n,n,m]` strides=`[s0,s1,s2]` -> shape=`[n,m]` strides=`[s0+s1, s2]`
647    pub fn diagonal_view(&self, axis_pairs: &[(usize, usize)]) -> Result<StridedView<'a, T, Op>> {
648        let ndim = self.ndim();
649        // Each pair ties two axes to one index, so the pairs partition the
650        // axes into classes. Track each class's root as its lowest axis; the
651        // result is then independent of pair order and of how pairs chain
652        // (tensor4all/strided-rs#329).
653        let mut root: tinyvec::TinyVec<[usize; INLINE_RANK]> = (0..ndim).collect();
654        fn find(root: &mut [usize], mut ax: usize) -> usize {
655            while root[ax] != ax {
656                root[ax] = root[root[ax]];
657                ax = root[ax];
658            }
659            ax
660        }
661        for &(a, b) in axis_pairs {
662            let hi = a.max(b);
663            if hi >= ndim {
664                return Err(StridedError::InvalidAxis {
665                    axis: hi,
666                    rank: ndim,
667                });
668            }
669            if a == b {
670                return Err(StridedError::InvalidAxis {
671                    axis: a,
672                    rank: ndim,
673                });
674            }
675            let (ra, rb) = (find(&mut root, a), find(&mut root, b));
676            root[ra.max(rb)] = ra.min(rb);
677        }
678
679        // Every class collapses onto its root: the root's stride sums the
680        // strides of all axes in the class and its dim is their minimum. A
681        // root is lower than every other axis of its class, so it has already
682        // been kept when a later member folds into it.
683        let mut dims: AxisVec = AxisVec::new();
684        let mut strides: StrideVec = StrideVec::new();
685        let mut position: tinyvec::TinyVec<[usize; INLINE_RANK]> =
686            tinyvec::TinyVec::with_capacity(ndim);
687        for ax in 0..ndim {
688            let r = find(&mut root, ax);
689            if r == ax {
690                position.push(dims.len());
691                dims.push(self.dims()[ax]);
692                strides.push(self.strides()[ax]);
693            } else {
694                position.push(usize::MAX);
695                let p = position[r];
696                strides[p] = strides[p]
697                    .checked_add(self.strides()[ax])
698                    .ok_or(StridedError::OffsetOverflow)?;
699                dims[p] = dims[p].min(self.dims()[ax]);
700            }
701        }
702
703        // A fused stride sums several input strides, so the result carries no
704        // bound proof of its own and is validated here instead
705        // (tensor4all/strided-rs#204).
706        validate_bounds(self.data().len(), &dims, &strides, self.offset())?;
707
708        Ok(from_meta(self.data(), &dims, &strides, self.offset()))
709    }
710
711    /// Broadcast this view to a target shape.
712    ///
713    /// Size-1 dimensions are expanded (stride set to 0) to match target.
714    ///
715    /// # Errors
716    ///
717    /// Returns [`StridedError::RankMismatch`] when `target_dims` does not
718    /// have one entry per axis, and [`StridedError::ShapeMismatch`] when an
719    /// axis is neither already the target extent nor of size one.
720    pub fn broadcast(&self, target_dims: &[usize]) -> Result<StridedView<'a, T, Op>> {
721        if self.dims().len() != target_dims.len() {
722            return Err(StridedError::RankMismatch(
723                self.dims().len(),
724                target_dims.len(),
725            ));
726        }
727        let mut new_strides = StrideVec::with_capacity(self.dims().len());
728        for i in 0..self.dims().len() {
729            if self.dims()[i] == target_dims[i] {
730                new_strides.push(self.strides()[i]);
731            } else if self.dims()[i] == 1 {
732                new_strides.push(0);
733            } else {
734                return Err(StridedError::ShapeMismatch(
735                    self.dims().to_vec(),
736                    target_dims.to_vec(),
737                ));
738            }
739        }
740        Ok(from_meta(self.data, target_dims, &new_strides, self.offset))
741    }
742}
743
744/// Composition methods: require `T: ElementOpApply` and `Op: ComposableElementOp<T>`.
745impl<'a, T: Copy + ElementOpApply, Op: ComposableElementOp<T>> StridedView<'a, T, Op> {
746    /// Transpose a 2D view: reverses dimensions and composes the Transpose element op.
747    ///
748    /// Julia equivalent: `Base.transpose(a::AbstractStridedView{<:Any, 2})`
749    ///
750    /// # Errors
751    ///
752    /// Returns [`StridedError::RankMismatch`] when the view is not 2-D.
753    pub fn transpose_2d(&self) -> Result<StridedView<'a, T, Op::ComposeTranspose>> {
754        if self.dims().len() != 2 {
755            return Err(StridedError::RankMismatch(self.dims().len(), 2));
756        }
757        Ok(from_meta(
758            self.data,
759            &[self.dims()[1], self.dims()[0]],
760            &[self.strides()[1], self.strides()[0]],
761            self.offset,
762        ))
763    }
764
765    /// Adjoint (conjugate transpose) of a 2D view.
766    ///
767    /// Julia equivalent: `Base.adjoint(a::AbstractStridedView{<:Any, 2})`
768    ///
769    /// # Errors
770    ///
771    /// Returns [`StridedError::RankMismatch`] when the view is not 2-D.
772    pub fn adjoint_2d(&self) -> Result<StridedView<'a, T, Op::ComposeAdjoint>> {
773        if self.dims().len() != 2 {
774            return Err(StridedError::RankMismatch(self.dims().len(), 2));
775        }
776        Ok(from_meta(
777            self.data,
778            &[self.dims()[1], self.dims()[0]],
779            &[self.strides()[1], self.strides()[0]],
780            self.offset,
781        ))
782    }
783
784    /// Complex conjugate (compose Conj without changing dims/strides).
785    ///
786    /// Julia equivalent: `Base.conj(a::AbstractStridedView)`
787    #[inline]
788    pub fn conj(&self) -> StridedView<'a, T, Op::ComposeConj> {
789        StridedView {
790            ptr: self.ptr,
791            data: self.data,
792            meta: self.meta.clone(),
793            offset: self.offset,
794            _op: PhantomData,
795        }
796    }
797}
798
799/// Element access: requires `Op: ElementOp<T>`.
800impl<'a, T: Copy, Op: ElementOp<T>> StridedView<'a, T, Op> {
801    /// Get an element with the element operation applied.
802    ///
803    /// # Panics
804    ///
805    /// Panics if `indices.len()` is not the view's rank, an index is out of
806    /// bounds, or the indexed offset does not fit `isize`.
807    pub fn get(&self, indices: &[usize]) -> T {
808        let offset = indexed_offset(self.dims(), self.strides(), indices, 0);
809        // SAFETY: `indexed_offset` (view.rs:240) asserts the index count and
810        // `index < dims[i]`, so the offset it returns lies within the reachable
811        // extent that `validate_bounds` (view.rs:187) proved stays inside
812        // `data` for this view's construction (or that the `new_unchecked`
813        // contract promised). A view from `StridedArray::view`
814        // (view.rs:1461) carries the same proof; see the comment there.
815        Op::apply(unsafe { *self.ptr.offset(offset) })
816    }
817
818    /// Get an element without bounds checking.
819    ///
820    /// # Safety
821    ///
822    /// `indices.len()` must equal `self.ndim()`, and `indices[i] < self.dims()[i]`
823    /// for every axis `i`.
824    ///
825    /// A shorter `indices` does not mean "the missing axes are indexed with 0":
826    /// the loop below skips the axes it was not given, so on a view with a
827    /// zero-extent axis it dereferences the view's dangling base pointer.
828    /// Debug builds reject a wrong `indices.len()` with `debug_assert_eq!`.
829    #[inline]
830    pub unsafe fn get_unchecked(&self, indices: &[usize]) -> T {
831        debug_assert_eq!(indices.len(), self.ndim(), "wrong number of indices");
832        let mut idx = 0isize;
833        for (i, &index) in indices.iter().enumerate() {
834            idx += index as isize * self.strides()[i];
835        }
836        // SAFETY: this function's `# Safety` contract (above) requires one
837        // index per axis, `indices.len() == self.ndim()`, with `index < dims[i]`
838        // for each. That makes `idx` an offset the view's construction proved
839        // reachable: `validate_bounds` (view.rs:187), the dense constructors
840        // (see `StridedArray::view`, view.rs:1461), or the `new_unchecked`
841        // contract. `ptr` is the view's base, so `ptr + idx` stays inside
842        // `data`. On a view with a zero-extent axis no index satisfies
843        // `index < dims[i]`, so the contract, not the debug-only arity check,
844        // is what keeps its dangling base unreached.
845        Op::apply(*self.ptr.offset(idx))
846    }
847}
848
849// ============================================================================
850// StridedViewMut
851// ============================================================================
852
853/// Dynamic-rank mutable strided view.
854///
855/// Always uses `Identity` element operation for write simplicity.
856/// Julia typically applies ops on the read side.
857pub struct StridedViewMut<'a, T> {
858    /// Element base: `base` plus `offset`, or a dangling pointer for an empty
859    /// layout. `get` and `set` go through it, so it stays cached.
860    ///
861    /// Nothing here reborrows the caller's `&mut [T]` any more: a stored slice
862    /// field was retagged at construction and by `data_mut`, which invalidated
863    /// this pointer and made every later `get`, `set`, and `as_view` access
864    /// undefined behavior.
865    ptr: *mut T,
866    /// Base of the whole backing slice.
867    ///
868    /// `base` with `src_len` is the handle `data` and `data_mut` re-derive the
869    /// slice from, so the backing extent stays independent of the shape (a
870    /// `[0]` shape still has a backing slice).
871    base: *mut T,
872    /// Length of the whole backing slice.
873    src_len: usize,
874    meta: ViewMeta,
875    offset: isize,
876    /// The view borrows the caller's slice for `'a` without holding it.
877    _marker: PhantomData<&'a mut [T]>,
878}
879
880// SAFETY: `StridedViewMut` uniquely owns its `&'a mut [T]` (held as
881// `PhantomData<&'a mut [T]>` plus the two raw pointers `base` and `ptr` derived
882// from it), and there is no `Sync` impl for it, so sending it moves that
883// exclusive borrow; `T: Send` is the bound `&mut [T]: Send` requires.
884unsafe impl<T: Send> Send for StridedViewMut<'_, T> {}
885
886impl<T: std::fmt::Debug> std::fmt::Debug for StridedViewMut<'_, T> {
887    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
888        f.debug_struct("StridedViewMut")
889            .field("dims", &self.meta.dims())
890            .field("strides", &self.meta.strides())
891            .field("offset", &self.offset)
892            .finish()
893    }
894}
895
896impl<'a, T> StridedViewMut<'a, T> {
897    /// A view from already-validated metadata.
898    #[inline]
899    fn from_meta(data: &'a mut [T], dims: &[usize], strides: &[isize], offset: isize) -> Self {
900        let meta = ViewMeta::from_slices(dims, strides);
901        let src_len = data.len();
902        let base = data.as_mut_ptr();
903        let ptr = if empty_layout(meta.dims()) {
904            empty_mut_ptr()
905        } else {
906            // SAFETY: as `base_ptr` above — `offset` was accepted by
907            // `validate_bounds` (view.rs:187) in `StridedViewMut::new`, or by a
908            // metadata transform that only reorders axes or zeroes strides, or
909            // came from the `new_unchecked` contract. `base` is this view's own
910            // live handle on `data` and the empty-layout branch above excludes
911            // the case where `offset` may point past it.
912            unsafe { base.offset(offset) }
913        };
914        Self {
915            ptr,
916            base,
917            src_len,
918            meta,
919            offset,
920            _marker: PhantomData,
921        }
922    }
923
924    /// Create a mutable view, copying the caller's metadata inline.
925    ///
926    /// `dims`, `strides`, and `offset` are in units of `T` (elements, not
927    /// bytes).
928    ///
929    /// The layout is copied, so it does not need to outlive the view and no
930    /// heap allocation happens at rank `<= INLINE_RANK`.
931    ///
932    /// # Errors
933    ///
934    /// Returns [`StridedError::StrideLengthMismatch`] when `dims` and
935    /// `strides` have different lengths, and
936    /// [`StridedError::OffsetOverflow`] when a reachable offset is not
937    /// representable: `dim - 1` of a non-unit extent does not fit `isize`, a
938    /// stride times that last index or the accumulated offsets overflow
939    /// `isize` or go negative, or the highest reachable offset is not below
940    /// the buffer length. A layout with a zero extent skips this check.
941    ///
942    /// # Examples
943    ///
944    /// ```
945    /// use strided_view::StridedViewMut;
946    ///
947    /// let mut data = [0.0f64; 4];
948    /// let mut view = StridedViewMut::<f64>::new(&mut data, &[2, 2], &[1, 2], 0).unwrap();
949    /// view.set(&[1, 1], 5.0);
950    /// assert_eq!(data[3], 5.0);
951    /// ```
952    #[inline]
953    pub fn new(
954        data: &'a mut [T],
955        dims: &[usize],
956        strides: &[isize],
957        offset: isize,
958    ) -> Result<Self> {
959        validate_bounds(data.len(), dims, strides, offset)?;
960        Ok(Self::from_meta(data, dims, strides, offset))
961    }
962
963    /// Create without bounds checking, copying the caller's metadata.
964    ///
965    /// `dims`, `strides`, and `offset` are in units of `T` (elements, not
966    /// bytes).
967    ///
968    /// # Safety
969    /// Caller must ensure all index combinations stay within bounds.
970    ///
971    /// # Examples
972    ///
973    /// ```
974    /// use strided_view::StridedViewMut;
975    ///
976    /// let mut data = [0.0f64; 4];
977    /// // SAFETY: the largest reachable offset, 1 * 1 + 1 * 2 = 3, is below
978    /// // `data.len() == 4`.
979    /// let view = unsafe { StridedViewMut::<f64>::new_unchecked(&mut data, &[2, 2], &[1, 2], 0) };
980    /// assert_eq!(view.ndim(), 2);
981    /// ```
982    #[inline]
983    pub unsafe fn new_unchecked(
984        data: &'a mut [T],
985        dims: &[usize],
986        strides: &[isize],
987        offset: isize,
988    ) -> Self {
989        Self::from_meta(data, dims, strides, offset)
990    }
991
992    /// Returns the shape (dimension sizes) of this view.
993    #[inline]
994    pub fn dims(&self) -> &[usize] {
995        self.meta.dims()
996    }
997
998    /// Returns the strides (in units of `T`) for each dimension.
999    #[inline]
1000    pub fn strides(&self) -> &[isize] {
1001        self.meta.strides()
1002    }
1003
1004    /// Returns the offset into the backing data, in units of `T` (elements, not bytes).
1005    #[inline]
1006    pub fn offset(&self) -> isize {
1007        self.offset
1008    }
1009
1010    /// Returns the number of dimensions (rank).
1011    #[inline]
1012    pub fn ndim(&self) -> usize {
1013        self.dims().len()
1014    }
1015
1016    /// Returns the total number of elements.
1017    ///
1018    /// # Panics
1019    ///
1020    /// Panics when the element count does not fit `usize`, which only a
1021    /// broadcast (stride-0) layout can reach.
1022    #[inline]
1023    pub fn len(&self) -> usize {
1024        element_count(self.dims())
1025    }
1026
1027    /// Returns `true` if any dimension is zero.
1028    #[inline]
1029    pub fn is_empty(&self) -> bool {
1030        self.dims().contains(&0)
1031    }
1032
1033    /// Raw const pointer to element at the view's base offset.
1034    #[inline]
1035    pub fn ptr(&self) -> *const T {
1036        self.ptr as *const T
1037    }
1038
1039    /// Raw mutable pointer to element at the view's base offset.
1040    #[inline]
1041    pub fn as_mut_ptr(&self) -> *mut T {
1042        self.ptr
1043    }
1044
1045    /// Returns a reference to the backing data slice.
1046    ///
1047    /// The length is the backing slice's, not the shape's: a view whose shape
1048    /// has a zero extent still reports the whole buffer.
1049    #[inline]
1050    pub fn data(&self) -> &[T] {
1051        // SAFETY: `base` is the caller's `data.as_mut_ptr()` and `src_len` is
1052        // that slice's length, both recorded at construction, so this rebuilds
1053        // exactly the borrowed slice. No length is derived from the shape, which
1054        // is why a zero-extent layout still reports the whole buffer. `T` is
1055        // initialized across it, and `&self` restricts this to a shared borrow.
1056        unsafe { std::slice::from_raw_parts(self.base, self.src_len) }
1057    }
1058
1059    /// Returns a mutable reference to the backing data slice.
1060    ///
1061    /// The slice is re-derived from the view's storage handle, so `ptr`, `get`,
1062    /// and `set` stay valid after the returned borrow ends.
1063    #[inline]
1064    pub fn data_mut(&mut self) -> &mut [T] {
1065        // SAFETY: as `data` above — the same `base`/`src_len` pair, so this
1066        // rebuilds the caller's slice rather than a shape-sized one. `&mut self`
1067        // keeps the returned slice the only reference into the view while it
1068        // lives. In a non-empty layout `ptr` is `base + offset`, derived without
1069        // a retag, so re-deriving the slice here does not invalidate it — the
1070        // property `get`/`set` rely on; an empty layout caches a dangling `ptr`
1071        // that no element access dereferences.
1072        unsafe { std::slice::from_raw_parts_mut(self.base, self.src_len) }
1073    }
1074
1075    /// Permute dimensions, consuming the mutable view.
1076    ///
1077    /// Returns a new mutable view with reordered dimensions and strides.
1078    /// Takes `self` by value to prevent aliasing of mutable views.
1079    ///
1080    /// # Errors
1081    ///
1082    /// Returns [`StridedError::RankMismatch`] when `perm` does not have one
1083    /// entry per axis, and [`StridedError::InvalidAxis`] when an entry
1084    /// names an axis outside the rank or repeats an axis.
1085    pub fn permute(self, perm: &[usize]) -> Result<StridedViewMut<'a, T>> {
1086        let rank = self.dims().len();
1087        if perm.len() != rank {
1088            return Err(StridedError::RankMismatch(perm.len(), rank));
1089        }
1090        let mut seen: tinyvec::TinyVec<[bool; INLINE_RANK]> = tinyvec::TinyVec::new();
1091        seen.resize(rank, false);
1092        for &p in perm {
1093            if p >= rank {
1094                return Err(StridedError::InvalidAxis { axis: p, rank });
1095            }
1096            if seen[p] {
1097                return Err(StridedError::InvalidAxis { axis: p, rank });
1098            }
1099            seen[p] = true;
1100        }
1101        let new_dims: AxisVec = perm.iter().map(|&p| self.dims()[p]).collect();
1102        let new_strides: StrideVec = perm.iter().map(|&p| self.strides()[p]).collect();
1103        Ok(Self {
1104            meta: ViewMeta::from_slices(&new_dims, &new_strides),
1105            ..self
1106        })
1107    }
1108
1109    /// Reborrow as an immutable view.
1110    ///
1111    /// The reborrow copies this view's metadata into the immutable view's
1112    /// inline storage, which allocates nothing up to [`INLINE_RANK`] and
1113    /// spills above it (the mutable owner always keeps its own copy).
1114    ///
1115    /// # Examples
1116    ///
1117    /// ```
1118    /// use strided_view::StridedViewMut;
1119    ///
1120    /// let mut data = [1.0f64, 2.0, 3.0];
1121    /// let view = StridedViewMut::<f64>::new(&mut data, &[3], &[1], 0).unwrap();
1122    /// let read = view.as_view();
1123    /// assert_eq!(read.get(&[2]), 3.0);
1124    /// ```
1125    #[inline]
1126    pub fn as_view(&self) -> StridedView<'_, T, Identity> {
1127        // SAFETY: `data()` re-derives the slice from this view's own handle
1128        // (`base` + `src_len`), and `ptr` is `base + offset` for the same
1129        // `offset`, so the immutable view ends up pointing at the same storage
1130        // the mutable view owns. A zero-extent layout yields a dangling pointer
1131        // on both sides (`empty_mut_ptr` here, the `empty_layout` branch of
1132        // `base_ptr` in the immutable view), so they agree there too. `&self`
1133        // keeps that storage exclusively borrowed for the returned view's
1134        // lifetime, so the shared view can only read it, and `T` is initialized
1135        // across the whole slice.
1136        unsafe { StridedView::new_unchecked(self.data(), self.dims(), self.strides(), self.offset) }
1137    }
1138}
1139
1140impl<'a, T: Copy> StridedViewMut<'a, T> {
1141    /// Get an element.
1142    ///
1143    /// # Panics
1144    ///
1145    /// Panics if `indices.len()` is not the view's rank, an index is out of
1146    /// bounds, or the indexed offset does not fit `isize`.
1147    pub fn get(&self, indices: &[usize]) -> T {
1148        let offset = indexed_offset(self.dims(), self.strides(), indices, 0);
1149        // SAFETY: in a non-empty layout `ptr` is `base + offset`, derived from
1150        // the caller's `&'a mut [T]` through raw pointers only, so a reborrow of
1151        // the backing slice does not invalidate it: `data_mut` re-derives that
1152        // slice from `base` and never rewrites `ptr`, and offsetting a raw
1153        // pointer keeps `base`'s provenance. (An empty layout caches a dangling
1154        // `ptr`, but no index satisfies `index < dims[i]` there, so this access
1155        // is unreachable.) `indexed_offset` (view.rs:240) asserts the index
1156        // count and `index < dims[i]`, so the relative offset it returns keeps
1157        // `ptr + offset` inside the extent `validate_bounds` (view.rs:187)
1158        // proved reachable, i.e. inside `base..base + src_len`, where every
1159        // element is initialized because the view borrows an initialized
1160        // `&'a mut [T]` and no method shortens that borrow.
1161        unsafe { *self.ptr.offset(offset) }
1162    }
1163
1164    /// Set an element.
1165    ///
1166    /// # Panics
1167    ///
1168    /// Panics if `indices.len()` is not the view's rank, an index is out of
1169    /// bounds, or the indexed offset does not fit `isize`.
1170    pub fn set(&mut self, indices: &[usize], value: T) {
1171        let offset = indexed_offset(self.dims(), self.strides(), indices, 0);
1172        // SAFETY: as `get` above — the same `ptr` survives an earlier `data_mut`
1173        // reborrow, and `indexed_offset` (view.rs:240) bounds-checks every index,
1174        // so the store lands inside `base..base + src_len`. `&mut self` makes
1175        // this the only access through the view for the call, and the view holds
1176        // the sole `&'a mut [T]` borrow of that storage, so nothing else can
1177        // alias the written place.
1178        unsafe {
1179            *self.ptr.offset(offset) = value;
1180        }
1181    }
1182}
1183
1184// ============================================================================
1185// StridedArray
1186// ============================================================================
1187
1188/// Owned strided multidimensional array.
1189///
1190/// Supports both column-major (Julia default) and row-major (C default) layouts.
1191pub struct StridedArray<T> {
1192    data: Vec<T>,
1193    meta: ViewMeta,
1194    offset: isize,
1195}
1196
1197impl<T: std::fmt::Debug> std::fmt::Debug for StridedArray<T> {
1198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1199        f.debug_struct("StridedArray")
1200            .field("dims", &self.meta.dims())
1201            .field("strides", &self.meta.strides())
1202            .field("offset", &self.offset)
1203            .finish()
1204    }
1205}
1206
1207impl<T: Clone> Clone for StridedArray<T> {
1208    fn clone(&self) -> Self {
1209        Self {
1210            data: self.data.clone(),
1211            meta: self.meta.clone(),
1212            offset: self.offset,
1213        }
1214    }
1215}
1216
1217impl<T: Clone + Default> StridedArray<T> {
1218    /// Create a column-major (Julia default) tensor filled with Default values.
1219    ///
1220    /// The shape and strides are stored inline, so a rank `<= INLINE_RANK`
1221    /// tensor allocates only its element buffer.
1222    ///
1223    /// # Examples
1224    ///
1225    /// ```
1226    /// use strided_view::StridedArray;
1227    ///
1228    /// let a = StridedArray::<f64>::col_major(&[2, 3]);
1229    /// assert_eq!(a.dims(), &[2, 3]);
1230    /// assert_eq!(a.strides(), &[1, 2]);
1231    /// ```
1232    ///
1233    /// # Panics
1234    ///
1235    /// Panics when the element count or a stride does not fit `isize`; use
1236    /// [`Self::try_col_major`] to get [`StridedError::OffsetOverflow`] instead.
1237    pub fn col_major(dims: &[usize]) -> Self {
1238        Self::try_col_major(dims).expect("col_major: shape overflows isize")
1239    }
1240
1241    /// Fallible [`Self::col_major`].
1242    ///
1243    /// # Errors
1244    ///
1245    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1246    /// stride does not fit `isize`.
1247    ///
1248    /// # Examples
1249    ///
1250    /// ```
1251    /// use strided_view::{StridedArray, StridedError};
1252    ///
1253    /// assert_eq!(StridedArray::<f64>::try_col_major(&[2, 3]).unwrap().strides(), &[1, 2]);
1254    /// assert!(matches!(
1255    ///     StridedArray::<f64>::try_col_major(&[1 << 62, 4]),
1256    ///     Err(StridedError::OffsetOverflow)
1257    /// ));
1258    /// ```
1259    pub fn try_col_major(dims: &[usize]) -> Result<Self> {
1260        let strides = checked_col_major_strides(dims)?;
1261        let total = checked_element_count(dims)?;
1262        Ok(Self {
1263            data: vec![T::default(); total],
1264            meta: ViewMeta::from_slices(dims, &strides),
1265            offset: 0,
1266        })
1267    }
1268
1269    /// Create a row-major (C default) tensor filled with Default values.
1270    ///
1271    /// The shape and strides are stored inline, so a rank `<= INLINE_RANK`
1272    /// tensor allocates only its element buffer.
1273    ///
1274    /// # Examples
1275    ///
1276    /// ```
1277    /// use strided_view::StridedArray;
1278    ///
1279    /// let a = StridedArray::<f64>::row_major(&[2, 3]);
1280    /// assert_eq!(a.dims(), &[2, 3]);
1281    /// assert_eq!(a.strides(), &[3, 1]);
1282    /// ```
1283    ///
1284    /// # Panics
1285    ///
1286    /// Panics when the element count or a stride does not fit `isize`; use
1287    /// [`Self::try_row_major`] to get [`StridedError::OffsetOverflow`] instead.
1288    pub fn row_major(dims: &[usize]) -> Self {
1289        Self::try_row_major(dims).expect("row_major: shape overflows isize")
1290    }
1291
1292    /// Fallible [`Self::row_major`].
1293    ///
1294    /// # Errors
1295    ///
1296    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1297    /// stride does not fit `isize`.
1298    pub fn try_row_major(dims: &[usize]) -> Result<Self> {
1299        let strides = checked_row_major_strides(dims)?;
1300        let total = checked_element_count(dims)?;
1301        Ok(Self {
1302            data: vec![T::default(); total],
1303            meta: ViewMeta::from_slices(dims, &strides),
1304            offset: 0,
1305        })
1306    }
1307
1308    /// Create a column-major tensor with values produced by a function.
1309    ///
1310    /// The function is called with indices in column-major iteration order.
1311    ///
1312    /// # Panics
1313    ///
1314    /// Panics when the element count or a stride does not fit `isize`; use
1315    /// [`Self::try_from_fn_col_major`] to get [`StridedError::OffsetOverflow`] instead.
1316    pub fn from_fn_col_major(dims: &[usize], f: impl FnMut(&[usize]) -> T) -> Self {
1317        Self::try_from_fn_col_major(dims, f).expect("from_fn_col_major: shape overflows isize")
1318    }
1319
1320    /// Fallible [`Self::from_fn_col_major`]; `f` is not called on error.
1321    ///
1322    /// # Errors
1323    ///
1324    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1325    /// stride does not fit `isize`.
1326    pub fn try_from_fn_col_major(dims: &[usize], mut f: impl FnMut(&[usize]) -> T) -> Result<Self> {
1327        let strides = checked_col_major_strides(dims)?;
1328        let total = checked_element_count(dims)?;
1329        let rank = dims.len();
1330        let mut data = Vec::with_capacity(total);
1331        let mut idx: AxisVec = AxisVec::new();
1332        idx.resize(rank, 0usize);
1333        // Borrow the cursor once; indexing the `TinyVec` per access would pay
1334        // its inline/heap match in the element-count loop.
1335        let idx: &mut [usize] = &mut idx[..];
1336        for _ in 0..total {
1337            data.push(f(idx));
1338            for d in 0..rank {
1339                idx[d] += 1;
1340                if idx[d] < dims[d] {
1341                    break;
1342                }
1343                idx[d] = 0;
1344            }
1345        }
1346        Ok(Self {
1347            data,
1348            meta: ViewMeta::from_slices(dims, &strides),
1349            offset: 0,
1350        })
1351    }
1352
1353    /// Create a row-major tensor with values produced by a function.
1354    ///
1355    /// The function is called with indices in row-major iteration order.
1356    ///
1357    /// # Panics
1358    ///
1359    /// Panics when the element count or a stride does not fit `isize`; use
1360    /// [`Self::try_from_fn_row_major`] to get [`StridedError::OffsetOverflow`] instead.
1361    pub fn from_fn_row_major(dims: &[usize], f: impl FnMut(&[usize]) -> T) -> Self {
1362        Self::try_from_fn_row_major(dims, f).expect("from_fn_row_major: shape overflows isize")
1363    }
1364
1365    /// Fallible [`Self::from_fn_row_major`]; `f` is not called on error.
1366    ///
1367    /// # Errors
1368    ///
1369    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1370    /// stride does not fit `isize`.
1371    pub fn try_from_fn_row_major(dims: &[usize], mut f: impl FnMut(&[usize]) -> T) -> Result<Self> {
1372        let strides = checked_row_major_strides(dims)?;
1373        let total = checked_element_count(dims)?;
1374        let rank = dims.len();
1375        let mut data = Vec::with_capacity(total);
1376        let mut idx: AxisVec = AxisVec::new();
1377        idx.resize(rank, 0usize);
1378        // Borrow the cursor once; see `from_fn_col_major`.
1379        let idx: &mut [usize] = &mut idx[..];
1380        for _ in 0..total {
1381            data.push(f(idx));
1382            for d in (0..rank).rev() {
1383                idx[d] += 1;
1384                if idx[d] < dims[d] {
1385                    break;
1386                }
1387                idx[d] = 0;
1388            }
1389        }
1390        Ok(Self {
1391            data,
1392            meta: ViewMeta::from_slices(dims, &strides),
1393            offset: 0,
1394        })
1395    }
1396}
1397
1398impl<T> StridedArray<T> {
1399    /// Create from raw parts.
1400    ///
1401    /// `dims`, `strides`, and `offset` are in units of `T` (elements, not
1402    /// bytes).
1403    ///
1404    /// # Errors
1405    ///
1406    /// Returns [`StridedError::StrideLengthMismatch`] when `dims` and
1407    /// `strides` have different lengths, and
1408    /// [`StridedError::OffsetOverflow`] when a reachable offset is not
1409    /// representable: `dim - 1` of a non-unit extent does not fit `isize`, a
1410    /// stride times that last index or the accumulated offsets overflow
1411    /// `isize` or go negative, or the highest reachable offset is not below
1412    /// the buffer length. A layout with a zero extent skips this check.
1413    pub fn from_parts(
1414        data: Vec<T>,
1415        dims: &[usize],
1416        strides: &[isize],
1417        offset: isize,
1418    ) -> Result<Self> {
1419        validate_bounds(data.len(), dims, strides, offset)?;
1420        Ok(Self {
1421            data,
1422            meta: ViewMeta::from_slices(dims, strides),
1423            offset,
1424        })
1425    }
1426
1427    /// Returns the shape (dimension sizes) of this array.
1428    #[inline]
1429    pub fn dims(&self) -> &[usize] {
1430        self.meta.dims()
1431    }
1432
1433    /// Returns the strides (in units of `T`) for each dimension.
1434    #[inline]
1435    pub fn strides(&self) -> &[isize] {
1436        self.meta.strides()
1437    }
1438
1439    /// Returns the number of dimensions (rank).
1440    #[inline]
1441    pub fn ndim(&self) -> usize {
1442        self.dims().len()
1443    }
1444
1445    /// Returns the total number of elements.
1446    ///
1447    /// # Panics
1448    ///
1449    /// Panics when the element count does not fit `usize`, which only a
1450    /// broadcast (stride-0) layout can reach.
1451    #[inline]
1452    pub fn len(&self) -> usize {
1453        element_count(self.dims())
1454    }
1455
1456    /// Returns `true` if any dimension is zero.
1457    #[inline]
1458    pub fn is_empty(&self) -> bool {
1459        self.dims().contains(&0)
1460    }
1461
1462    /// Returns a reference to the backing data slice.
1463    #[inline]
1464    pub fn data(&self) -> &[T] {
1465        &self.data
1466    }
1467
1468    /// Returns a mutable reference to the backing data slice.
1469    #[inline]
1470    pub fn data_mut(&mut self) -> &mut [T] {
1471        &mut self.data
1472    }
1473
1474    /// Create an immutable view over this tensor.
1475    #[inline]
1476    pub fn view(&self) -> StridedView<'_, T> {
1477        let ptr = if self.is_empty() {
1478            empty_const_ptr()
1479        } else {
1480            // SAFETY: `offset` is either 0 from a constructor or was accepted by
1481            // `validate_bounds` in `StridedArray::from_parts` (view.rs:1398), so
1482            // `data.as_ptr() + offset` stays inside `data`. The empty branch
1483            // above excludes a zero-sized layout, whose offset need not be
1484            // reachable. The view built below also needs the whole reachable
1485            // extent inside `data` (its `get` relies on it): `from_parts` proved
1486            // that with `validate_bounds`, and every dense constructor
1487            // (`try_col_major`, view.rs:1247, and its row-major, `from_fn`,
1488            // `from_buffer` and uninit siblings) stores exactly
1489            // `checked_element_count(dims)` (view.rs:266) elements under
1490            // `checked_dense_strides` (view.rs:292), whose highest offset is that
1491            // count minus one. `permuted` only reorders axes, and `data_mut`
1492            // hands out a slice, which cannot change the length.
1493            unsafe { self.data.as_ptr().offset(self.offset) }
1494        };
1495        StridedView {
1496            ptr,
1497            data: &self.data,
1498            meta: self.meta.clone(),
1499            offset: self.offset,
1500            _op: PhantomData,
1501        }
1502    }
1503
1504    /// Create a mutable view over this tensor.
1505    #[inline]
1506    pub fn view_mut(&mut self) -> StridedViewMut<'_, T> {
1507        let src_len = self.data.len();
1508        let base = self.data.as_mut_ptr();
1509        let ptr = if self.is_empty() {
1510            empty_mut_ptr()
1511        } else {
1512            // SAFETY: as `view` above — `self.offset` is either 0 from a
1513            // constructor or was accepted by `validate_bounds` in
1514            // `StridedArray::from_parts` (view.rs:1398), and `&mut self` keeps
1515            // this reborrow exclusive. The empty branch above excludes a
1516            // zero-sized layout, whose offset need not be reachable. The whole
1517            // reachable extent stays inside `data` for the same reasons given in
1518            // `view`, which `StridedViewMut::get`/`set` rely on.
1519            unsafe { base.offset(self.offset) }
1520        };
1521        StridedViewMut {
1522            ptr,
1523            base,
1524            src_len,
1525            meta: self.meta.clone(),
1526            offset: self.offset,
1527            _marker: PhantomData,
1528        }
1529    }
1530
1531    /// Permute dimensions (metadata-only reorder, no data copy).
1532    ///
1533    /// Returns a new array with reordered dims and strides.
1534    /// The underlying data buffer is not touched.
1535    ///
1536    /// # Errors
1537    ///
1538    /// Returns [`StridedError::RankMismatch`] when `perm` does not have one
1539    /// entry per axis, and [`StridedError::InvalidAxis`] when an entry
1540    /// names an axis outside the rank or repeats an axis.
1541    pub fn permuted(self, perm: &[usize]) -> Result<Self> {
1542        let rank = self.dims().len();
1543        if perm.len() != rank {
1544            return Err(StridedError::RankMismatch(perm.len(), rank));
1545        }
1546        let mut seen: tinyvec::TinyVec<[bool; INLINE_RANK]> = tinyvec::TinyVec::new();
1547        seen.resize(rank, false);
1548        for &p in perm {
1549            if p >= rank {
1550                return Err(StridedError::InvalidAxis { axis: p, rank });
1551            }
1552            if seen[p] {
1553                return Err(StridedError::InvalidAxis { axis: p, rank });
1554            }
1555            seen[p] = true;
1556        }
1557        let new_dims: AxisVec = perm.iter().map(|&p| self.dims()[p]).collect();
1558        let new_strides: StrideVec = perm.iter().map(|&p| self.strides()[p]).collect();
1559        Ok(Self {
1560            data: self.data,
1561            meta: ViewMeta::from_slices(&new_dims, &new_strides),
1562            offset: self.offset,
1563        })
1564    }
1565
1566    /// Consume the array and return the backing `Vec<T>`.
1567    pub fn into_data(self) -> Vec<T> {
1568        self.data
1569    }
1570
1571    /// Iterate over all elements in memory order.
1572    pub fn iter(&self) -> std::slice::Iter<'_, T> {
1573        self.data.iter()
1574    }
1575
1576    /// Mutable iteration over all elements in memory order.
1577    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
1578        self.data.iter_mut()
1579    }
1580}
1581
1582impl<T: Default> StridedArray<T> {
1583    /// Create a column-major tensor reusing an existing buffer.
1584    ///
1585    /// If `buf` has at least `product(dims)` elements, it is truncated and
1586    /// zeroed.  Otherwise a fresh buffer is allocated.
1587    ///
1588    /// # Panics
1589    ///
1590    /// Panics when the element count or a stride does not fit `isize`; use
1591    /// [`Self::try_col_major_from_buffer`] to get
1592    /// [`StridedError::OffsetOverflow`] instead.
1593    pub fn col_major_from_buffer(buf: Vec<T>, dims: &[usize]) -> Self {
1594        Self::try_col_major_from_buffer(buf, dims)
1595            .expect("col_major_from_buffer: shape overflows isize")
1596    }
1597
1598    /// Fallible [`Self::col_major_from_buffer`]; `buf` is dropped on error.
1599    ///
1600    /// # Errors
1601    ///
1602    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1603    /// stride does not fit `isize`.
1604    pub fn try_col_major_from_buffer(mut buf: Vec<T>, dims: &[usize]) -> Result<Self> {
1605        let strides = checked_col_major_strides(dims)?;
1606        let total = checked_element_count(dims)?;
1607        if buf.len() >= total {
1608            buf.truncate(total);
1609        } else {
1610            buf.resize_with(total, T::default);
1611        }
1612        // Zero the reused region
1613        for v in buf.iter_mut() {
1614            *v = T::default();
1615        }
1616        Ok(Self {
1617            data: buf,
1618            meta: ViewMeta::from_slices(dims, &strides),
1619            offset: 0,
1620        })
1621    }
1622}
1623
1624impl<T: Copy> StridedArray<T> {
1625    /// Create a column-major tensor with **uninitialized** data.
1626    ///
1627    /// The element type of the returned array is [`MaybeUninit<T>`], so no slot
1628    /// ever claims to hold a `T` before the caller wrote one — which is what
1629    /// `bool`, `char` and reference elements need (#413).
1630    ///
1631    /// # Safety
1632    ///
1633    /// This is the pre-#413 contract kept on the signature: a slot may be read
1634    /// through [`MaybeUninit::assume_init`] only after it was written. Allocating
1635    /// the slots carries no memory-safety precondition of its own; the per-slot
1636    /// rule is the one [`MaybeUninit`] already states.
1637    ///
1638    /// # Panics
1639    ///
1640    /// Panics when the element count or a stride does not fit `isize`; use
1641    /// [`Self::try_col_major_uninit`] to get [`StridedError::OffsetOverflow`]
1642    /// instead.
1643    ///
1644    /// # Examples
1645    ///
1646    /// ```
1647    /// use std::mem::MaybeUninit;
1648    /// use strided_view::StridedArray;
1649    ///
1650    /// // SAFETY: each slot is written below before it is read.
1651    /// let mut a = unsafe { StridedArray::<bool>::col_major_uninit(&[2]) };
1652    /// a.set(&[0], MaybeUninit::new(true));
1653    /// a.set(&[1], MaybeUninit::new(false));
1654    /// // SAFETY: both slots were written above.
1655    /// assert!(unsafe { a.get(&[0]).assume_init() });
1656    /// ```
1657    pub unsafe fn col_major_uninit(dims: &[usize]) -> StridedArray<MaybeUninit<T>> {
1658        // SAFETY: `try_col_major_uninit` has the same contract as this function
1659        // (view.rs:1618), which our caller accepted: read a slot only after
1660        // writing it. This call reads nothing.
1661        Self::try_col_major_uninit(dims).expect("col_major_uninit: shape overflows isize")
1662    }
1663
1664    /// Fallible [`Self::col_major_uninit`].
1665    ///
1666    /// # Safety
1667    ///
1668    /// As [`Self::col_major_uninit`].
1669    ///
1670    /// # Errors
1671    ///
1672    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1673    /// stride does not fit `isize`.
1674    pub unsafe fn try_col_major_uninit(dims: &[usize]) -> Result<StridedArray<MaybeUninit<T>>> {
1675        let strides = checked_col_major_strides(dims)?;
1676        let total = checked_element_count(dims)?;
1677        Ok(StridedArray {
1678            data: vec![MaybeUninit::uninit(); total],
1679            meta: ViewMeta::from_slices(dims, &strides),
1680            offset: 0,
1681        })
1682    }
1683
1684    /// Reuse an existing buffer as a column-major tensor **without zeroing**.
1685    ///
1686    /// The buffer is `Vec<MaybeUninit<T>>` for the same reason as
1687    /// [`Self::col_major_uninit`]: a slot the caller has not written yet is not a
1688    /// `T` (#413). Slots the buffer already holds are kept as they are.
1689    ///
1690    /// # Safety
1691    ///
1692    /// As [`Self::col_major_uninit`]: read a slot with
1693    /// [`MaybeUninit::assume_init`] only after it was written.
1694    ///
1695    /// # Panics
1696    ///
1697    /// Panics when the element count or a stride does not fit `isize`; use
1698    /// [`Self::try_col_major_from_buffer_uninit`] to get
1699    /// [`StridedError::OffsetOverflow`] instead.
1700    pub unsafe fn col_major_from_buffer_uninit(
1701        buf: Vec<MaybeUninit<T>>,
1702        dims: &[usize],
1703    ) -> StridedArray<MaybeUninit<T>> {
1704        // SAFETY: `try_col_major_from_buffer_uninit` has the same contract as
1705        // this function (view.rs:1618), which our caller accepted: read a slot
1706        // only after writing it. This call reads nothing.
1707        Self::try_col_major_from_buffer_uninit(buf, dims)
1708            .expect("col_major_from_buffer_uninit: shape overflows isize")
1709    }
1710
1711    /// Fallible [`Self::col_major_from_buffer_uninit`]; `buf` is dropped on
1712    /// error.
1713    ///
1714    /// # Safety
1715    ///
1716    /// As [`Self::col_major_uninit`].
1717    ///
1718    /// # Errors
1719    ///
1720    /// Returns [`StridedError::OffsetOverflow`] when the element count or a
1721    /// stride does not fit `isize`.
1722    pub unsafe fn try_col_major_from_buffer_uninit(
1723        mut buf: Vec<MaybeUninit<T>>,
1724        dims: &[usize],
1725    ) -> Result<StridedArray<MaybeUninit<T>>> {
1726        let strides = checked_col_major_strides(dims)?;
1727        let total = checked_element_count(dims)?;
1728        // Truncates or grows to the shape; the retained prefix keeps whatever the
1729        // caller already put in it.
1730        buf.resize(total, MaybeUninit::uninit());
1731        Ok(StridedArray {
1732            data: buf,
1733            meta: ViewMeta::from_slices(dims, &strides),
1734            offset: 0,
1735        })
1736    }
1737}
1738
1739impl<T: Copy> StridedArray<T> {
1740    /// Get an element by multi-dimensional index.
1741    ///
1742    /// # Panics
1743    ///
1744    /// Panics if `indices.len()` is not the array's rank, an index is out of
1745    /// bounds, or the indexed offset does not fit `isize`.
1746    pub fn get(&self, indices: &[usize]) -> T {
1747        self.view().get(indices)
1748    }
1749
1750    /// Set an element by multi-dimensional index.
1751    ///
1752    /// # Panics
1753    ///
1754    /// Panics if `indices.len()` is not the array's rank, an index is out of
1755    /// bounds, or the indexed offset does not fit `isize`.
1756    pub fn set(&mut self, indices: &[usize], value: T) {
1757        let offset = indexed_offset(self.dims(), self.strides(), indices, self.offset);
1758        self.data[offset as usize] = value;
1759    }
1760}
1761
1762impl<T: Copy> Index<&[usize]> for StridedArray<T> {
1763    type Output = T;
1764
1765    fn index(&self, indices: &[usize]) -> &T {
1766        let offset = indexed_offset(self.dims(), self.strides(), indices, self.offset);
1767        &self.data[offset as usize]
1768    }
1769}
1770
1771impl<T: Copy> IndexMut<&[usize]> for StridedArray<T> {
1772    fn index_mut(&mut self, indices: &[usize]) -> &mut T {
1773        let offset = indexed_offset(self.dims(), self.strides(), indices, self.offset);
1774        &mut self.data[offset as usize]
1775    }
1776}
1777
1778// ============================================================================
1779// Tests
1780// ============================================================================
1781
1782#[cfg(test)]
1783mod tests;