Skip to main content

strided_view/
auxiliary.rs

1//! Auxiliary routines ported from StridedViews.jl/src/auxiliary.jl
2
3/// Compute the relative order of strides.
4///
5/// Returns a vector where `result[i]` is the rank of `strides[i]` among all non-zero strides.
6/// Zero strides have order 1.
7///
8/// Returns an inline [`crate::AxisVec`]: the result does not allocate at rank
9/// `<=` [`crate::INLINE_RANK`] and spills above it. This is the allocating form
10/// of [`index_order_into`].
11///
12/// # Examples
13///
14/// ```
15/// use strided_view::auxiliary::index_order;
16///
17/// let order = index_order(&[4, 1, 2]);
18/// assert_eq!(order.as_slice(), &[3, 1, 2]);
19/// ```
20///
21/// # Julia equivalent
22/// ```julia
23/// function indexorder(strides::NTuple{N,Int}) where {N}
24///     return ntuple(Val(N)) do i
25///         si = abs(strides[i])
26///         si == 0 && return 1
27///         k = 1
28///         for s in strides
29///             if s != 0 && abs(s) < si
30///                 k += 1
31///             end
32///         end
33///         return k
34///     end
35/// end
36/// ```
37pub fn index_order(strides: &[isize]) -> crate::AxisVec {
38    let mut result = crate::AxisVec::new();
39    result.resize(strides.len(), 1usize);
40    // The lengths agree by construction, so the only error cannot occur.
41    let _ = index_order_into(strides, &mut result);
42    result
43}
44
45/// [`index_order`] written into `out` instead of a new vector, so a caller
46/// with its own storage computes the order without allocating at any rank.
47///
48/// # Errors
49///
50/// [`crate::StridedError::StrideLengthMismatch`] when `out.len()` differs from
51/// `strides.len()`; nothing is written then.
52///
53/// # Examples
54///
55/// ```
56/// use strided_view::auxiliary::index_order_into;
57///
58/// let mut order = [0usize; 3];
59/// index_order_into(&[4, 1, 2], &mut order).unwrap();
60/// assert_eq!(order, [3, 1, 2]);
61/// ```
62pub fn index_order_into(strides: &[isize], out: &mut [usize]) -> crate::Result<()> {
63    if out.len() != strides.len() {
64        return Err(crate::StridedError::StrideLengthMismatch);
65    }
66    for (slot, &stride) in out.iter_mut().zip(strides) {
67        let si = stride.unsigned_abs();
68        *slot = if si == 0 {
69            1
70        } else {
71            1 + strides
72                .iter()
73                .filter(|&&s| s != 0 && s.unsigned_abs() < si)
74                .count()
75        };
76    }
77    Ok(())
78}
79
80#[cfg(test)]
81mod tests;