From 5cab54b288deeb4d1ab2de2df26bcc08915029e6 Mon Sep 17 00:00:00 2001 From: Jutho Haegeman Date: Tue, 24 Nov 2026 23:37:01 +0100 Subject: [PATCH 1/3] Move errors out of line, unroll stride normalization, extend unsafe_stridedview - Throw errors from `@noinline` helpers, with `LazyString` messages where they interpolate, so that building them does not end up in the callers. - `permutedims` indexes the size and strides with `@inbounds`, since the permutation has been checked; same for `_strides(::PermutedDimsArray)`. - `unsafe_stridedview(a::StridedView, size, strides, offset)` replaces the layout of a view while keeping its element type, parent and operation. The strides are used as given, so this also supports zero strides. - `_normalizestrides` is a fully unrolled scan, with the same results as before (checked against the previous implementation in the tests). Co-Authored-By: Claude Opus 5.5 --- src/auxiliary.jl | 56 +++++++++++++++++++++++++++++----------------- src/stridedview.jl | 56 +++++++++++++++++++++++++++++----------------- test/runtests.jl | 55 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 127 insertions(+), 40 deletions(-) diff --git a/src/auxiliary.jl b/src/auxiliary.jl index c543189..c419aff 100644 --- a/src/auxiliary.jl +++ b/src/auxiliary.jl @@ -1,5 +1,19 @@ # Auxiliary routines #--------------------- +# Errors are thrown from `@noinline` functions, so that building the exception and its +# message does not end up in the code of the (often inlined) callers. Messages with +# interpolation are `LazyString`s, so that they are only built when they are shown. +@noinline _throw_dimensionmismatch() = throw(DimensionMismatch()) +@noinline function _throw_invalidperm(N::Int, p) + throw(ArgumentError(lazy"Invalid permutation of length $N: $p")) +end +@noinline function _throw_reinterpret_eltype(S::Type, T::Type) + throw(ArgumentError(lazy"Cannot create StridedView with reinterpretation from $S to $T")) +end +@noinline function _throw_reinterpret_op() + throw(ArgumentError("Cannot create StridedView with reinterpretation from view with non-identity operation")) +end + # Check whether p is a valid permutation of length N _isperm(N::Integer, p::AbstractVector) = (length(p) == N && isperm(p)) _isperm(N::Integer, p::NTuple{M, Integer}) where {M} = (M == N && isperm(p)) @@ -30,20 +44,25 @@ function _simplifydims(size::Dims{N}, strides::Dims{N}) where {N} end # 'Normalize' the strides of a `StridedView`, i.e. strides associated with dimensions of -# size 1 have no intrinsic meaning and can be changed arbitrarily. If one of the dimensions -# has size zero, then the whole array has length zero, and all strides are ambiguous. All -# ambiguous strides are set to 1. -function _normalizestrides(size::Dims{N}, strides::Dims{N}) where {N} - for i in 1:N - if size[i] == 1 - newstride = i == 1 ? 1 : strides[i - 1] * size[i - 1] - strides = Base.setindex(strides, newstride, i) - elseif size[i] == 0 - return (1, Base.front(cumprod(size))...) - end - end - return strides +# size 1 have no intrinsic meaning and can be changed arbitrarily. They are set to the extent +# of the preceding dimension (stride times size), or 1 for leading dimensions of size 1, such +# that a size 1 dimension never prevents fusing its neighbours. If one of the dimensions has +# size zero, then the whole array has length zero, and all strides are ambiguous; they are +# set to those of a contiguous array. +# The strides are computed with a fully unrolled scan that carries the extent of the +# preceding dimension. +@inline function _normalizestrides(size::Dims{N}, strides::Dims{N}) where {N} + any(iszero, size) && return _contiguousstrides(size) + return first(_normalizestrides_scan(size, strides, 1)) +end +_normalizestrides_scan(::Tuple{}, ::Tuple{}, carry::Int) = ((), carry) +@inline function _normalizestrides_scan(size::Dims, strides::Dims, carry::Int) + s = ifelse(size[1] == 1, carry, strides[1]) + rest, _ = _normalizestrides_scan(tail(size), tail(strides), size[1] * s) + return (s, rest...), carry end +_contiguousstrides(::Tuple{}) = () +@inline _contiguousstrides(size::Dims) = (1, Base.front(cumprod(size))...) # 'Normalize' the layout of a DenseArray, in order to reduce the number of required # specializations in functions. The offset is adjusted to the start of `A` in the @@ -113,11 +132,11 @@ function _computereshapestrides( newsize::Tuple{}, oldsize::Dims{N}, strides::Dims{N} ) where {N} - all(isequal(1), oldsize) || throw(DimensionMismatch()) + all(isequal(1), oldsize) || _throw_dimensionmismatch() return () end function _computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{}) - all(isequal(1), newsize) || throw(DimensionMismatch()) + all(isequal(1), newsize) || _throw_dimensionmismatch() return newsize end function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N}) where {N} @@ -137,10 +156,7 @@ function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N return isnothing(stail) ? nothing : (s1, stail...) end else - if prod(newsize) != prod(oldsize) - throw(DimensionMismatch()) - else - return nothing - end + prod(newsize) == prod(oldsize) || _throw_dimensionmismatch() + return nothing end end diff --git a/src/stridedview.jl b/src/stridedview.jl index 3af05e0..4dda54f 100644 --- a/src/stridedview.jl +++ b/src/stridedview.jl @@ -58,16 +58,32 @@ end """ unsafe_stridedview(T, parent, size, strides, offset, op) + unsafe_stridedview(a::StridedView, size = size(a), strides = strides(a), offset = offset(a)) -Construct a `StridedView{T}` without normalizing `parent` and `strides`, which are assumed to -be normalized already, e.g. because they are taken from an existing `StridedView`. +Construct a `StridedView{T}` without normalizing `parent` and `strides`. + +The first form assumes these are normalized already, e.g. because they are taken from an +existing `StridedView`. The second form keeps the element type, parent and operation of `a` +and replaces its layout, which can have any number of dimensions. The strides are used as +given, so they need not be normalized: e.g. a stride of zero repeats the same element along +that dimension. + +!!! warning + No checks are performed: the caller is responsible for all indices in the new layout + being valid indices of the parent. """ -function unsafe_stridedview( +@inline function unsafe_stridedview( ::Type{T}, parent::DenseArray, size::NTuple{N, Int}, strides::NTuple{N, Int}, offset::Int, op::F ) where {T, N, F} return StridedView{T, N, typeof(parent), F}(parent, size, strides, offset, op) end +@inline function unsafe_stridedview( + a::StridedView{T}, size::NTuple{N, Int} = a.size, strides::NTuple{N, Int} = a.strides, + offset::Int = a.offset + ) where {T, N} + return unsafe_stridedview(T, a.parent, size, strides, offset, a.op) +end StridedView(a::StridedView) = a StridedView(a::Adjoint) = StridedView(a')' @@ -81,9 +97,8 @@ function StridedView(a::Base.ReinterpretArray{T, N}) where {T, N} b = StridedView(a.parent) S = eltype(b) isbitstype(T) && isbitstype(S) && sizeof(T) == sizeof(S) || - throw(ArgumentError("Cannot create StridedView with reinterpretation from $S to $T")) - b.op isa FN || - throw(ArgumentError("Cannot create StridedView with reinterpretation from view with non-identity operation")) + _throw_reinterpret_eltype(S, T) + b.op isa FN || _throw_reinterpret_op() return unsafe_stridedview(T, b.parent, size(b), strides(b), offset(b), identity) end @@ -118,7 +133,7 @@ _strides(a::Transpose{<:Any, <:AbstractVector}) = (stride(a.parent, 2), stride(a _strides(a::Transpose{<:Any, <:AbstractMatrix}) = reverse(strides(a.parent)) function _strides(a::PermutedDimsArray{T, N, perm}) where {T, N, perm} s = _strides(parent(a)) - return ntuple(d -> s[perm[d]], Val(N)) + return ntuple(d -> @inbounds(s[perm[d]]), Val(N)) # `perm` is a valid permutation end _strides(a::SubArray) = Base.substrides(_strides(a.parent), a.indices) @@ -155,10 +170,7 @@ end function Base.getindex(a::StridedView{T, N}, I::Vararg{SliceIndex, N}) where {T, N} newsize = _computeviewsize(a.size, I) newstrides = _normalizestrides(newsize, _computeviewstrides(a.strides, I)) - return unsafe_stridedview( - T, a.parent, newsize, newstrides, - a.offset + _computeviewoffset(a.strides, I), a.op - ) + return unsafe_stridedview(a, newsize, newstrides, a.offset + _computeviewoffset(a.strides, I)) end # Indexing directly into parent array @@ -192,11 +204,12 @@ function Base.conj(a::StridedView) return unsafe_stridedview(T, a.parent, a.size, a.strides, a.offset, newop) end -function Base.permutedims(a::StridedView{T, N}, p) where {T, N} - _isperm(N, p) || throw(ArgumentError("Invalid permutation of length $N: $p")) - newsize = ntuple(n -> size(a, p[n]), Val(N)) - newstrides = ntuple(n -> stride(a, p[n]), Val(N)) - return unsafe_stridedview(T, a.parent, newsize, _normalizestrides(newsize, newstrides), a.offset, a.op) +function Base.permutedims(a::StridedView{<:Any, N}, p) where {N} + _isperm(N, p) || _throw_invalidperm(N, p) + # `p` has been checked to be a permutation of `1:N` + newsize = ntuple(n -> @inbounds(a.size[p[n]]), Val(N)) + newstrides = ntuple(n -> @inbounds(a.strides[p[n]]), Val(N)) + return unsafe_stridedview(a, newsize, _normalizestrides(newsize, newstrides)) end LinearAlgebra.transpose(a::StridedView{<:Number, 2}) = permutedims(a, (2, 1)) @@ -267,19 +280,22 @@ function Base.show(io::IO, e::ReshapeException) msg = "Cannot reshape a StridedView with size $(e.oldsize) and strides $(e.strides) to newsize=$(e.newsize) without allocating, try `sreshape(copy(array), newsize)` or fall back to `reshape(array, newsize)`." return print(io, msg) end +@noinline function _throw_reshapeexception(newsize::Dims, oldsize::Dims, strides::Dims) + throw(ReshapeException(newsize, oldsize, strides)) +end # we cannot use Base.reshape, as this also accepts indices that might not preserve stridedness sreshape(a, args::Vararg{Int}) = sreshape(a, args) -function sreshape(a::StridedView{T}, newsize::Dims) where {T} +function sreshape(a::StridedView, newsize::Dims) size(a) == newsize && return a if any(isequal(0), newsize) - any(isequal(0), size(a)) || throw(DimensionMismatch()) + any(isequal(0), size(a)) || _throw_dimensionmismatch() newstrides = one.(newsize) else newstrides = _computereshapestrides(newsize, _simplifydims(size(a), strides(a))...) end - isnothing(newstrides) && throw(ReshapeException(newsize, size(a), strides(a))) - return unsafe_stridedview(T, a.parent, newsize, _normalizestrides(newsize, newstrides), a.offset, a.op) + isnothing(newstrides) && _throw_reshapeexception(newsize, size(a), strides(a)) + return unsafe_stridedview(a, newsize, _normalizestrides(newsize, newstrides)) end sreshape(a::AbstractArray, newsize::Dims) = sreshape(StridedView(a), newsize) diff --git a/test/runtests.jl b/test/runtests.jl index 3380206..dd06f15 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -259,6 +259,61 @@ if !is_buildkite end end + @testset "stride normalization" begin + # reference implementation (previous version of `_normalizestrides`) + function normalizestrides_ref(size::Dims{N}, strides::Dims{N}) where {N} + for i in 1:N + if size[i] == 1 + newstride = i == 1 ? 1 : strides[i - 1] * size[i - 1] + strides = Base.setindex(strides, newstride, i) + elseif size[i] == 0 + return (1, Base.front(cumprod(size))...) + end + end + return strides + end + @test @inferred(StridedViews._normalizestrides((), ())) == () + for N in 1:6, _ in 1:200 + sz = ntuple(_ -> rand((0, 1, 1, 2, 3)), N) + st = ntuple(_ -> rand(-5:20), N) + @test @inferred(StridedViews._normalizestrides(sz, st)) == + normalizestrides_ref(sz, st) + end + @test StridedViews._normalizestrides((1, 1, 3, 1, 2), (7, 7, 5, 7, 2)) == + (1, 1, 5, 15, 2) + end + + @testset "unsafe_stridedview with a StridedView" begin + A = randn(ComplexF64, 4, 3, 2) + B = conj(StridedView(A)) + @test StridedViews.unsafe_stridedview(B) === B + C = @inferred StridedViews.unsafe_stridedview(B, (4, 6), (1, 4)) + @test C isa StridedView{ComplexF64, 2, typeof(B.parent), typeof(conj)} + @test C == conj(reshape(A, (4, 6))) + # strides are used as given, e.g. zero strides for broadcasting + D = StridedViews.unsafe_stridedview(B, (4, 5), (1, 0), StridedViews.offset(B) + 4) + @test D == repeat(conj(A[:, 2, 1]), 1, 5) + @test strides(D) == (1, 0) + end + + @testset "errors" begin + B = StridedView(randn(2, 3, 4)) + err = try + permutedims(B, (1, 1, 2)) + catch e + e + end + @test err isa ArgumentError + @test err.msg == "Invalid permutation of length 3: (1, 1, 2)" + @test_throws ArgumentError permutedims(B, (1, 2)) + @test_throws ArgumentError permutedims(B, [3, 1]) + @test_throws DimensionMismatch sreshape(B, (5, 5)) + @test_throws StridedViews.ReshapeException sreshape(B[:, 1:2, :], (2, 8)) + @test_throws ArgumentError StridedView(reinterpret(Float32, randn(4))) + A = randn(ComplexF64, 4) + @test_throws ArgumentError StridedView(reinterpret(NTuple{2, Float64}, conj(StridedView(A)))) + end + @testset "views with StridedView" begin @testset for T in (Float32, Float64, ComplexF32, ComplexF64) A = randn(T, (10, 10, 10, 10)) From 1ab87080bbc3484ed31cbac2eda8bfde1553f189 Mon Sep 17 00:00:00 2001 From: Jutho Haegeman Date: Wed, 25 Nov 2026 00:23:57 +0100 Subject: [PATCH 2/3] Check slicing bounds, explain sreshape length mismatches, faster permutation check - Slicing a `StridedView` (`getindex` with ranges and colons, `view` and `sview`) now checks bounds; previously an out-of-range slice silently produced a view outside the parent. The check can be skipped with `@inbounds`. - `sreshape` checks the lengths up front, with a message that gives both sizes and lengths, instead of an empty `DimensionMismatch` from inside `_computereshapestrides`, whose checks were therefore redundant. - `_isperm` records the entries in a 64-bit mask for N <= 64, which is O(N) without branches or allocations, instead of `Base.isperm`, which is O(N^2) for tuples and allocates for vectors. Co-Authored-By: Claude Opus 5.5 --- src/auxiliary.jl | 53 ++++++++++++++++++++++++++++++++-------------- src/stridedview.jl | 21 ++++++++++++------ test/runtests.jl | 48 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 23 deletions(-) diff --git a/src/auxiliary.jl b/src/auxiliary.jl index c419aff..0652bf5 100644 --- a/src/auxiliary.jl +++ b/src/auxiliary.jl @@ -3,7 +3,9 @@ # Errors are thrown from `@noinline` functions, so that building the exception and its # message does not end up in the code of the (often inlined) callers. Messages with # interpolation are `LazyString`s, so that they are only built when they are shown. -@noinline _throw_dimensionmismatch() = throw(DimensionMismatch()) +@noinline function _throw_reshape_dimensionmismatch(oldsize::Dims, newsize::Dims) + throw(DimensionMismatch(lazy"Cannot reshape a StridedView of size $oldsize (length $(prod(oldsize))) to size $newsize (length $(prod(newsize)))")) +end @noinline function _throw_invalidperm(N::Int, p) throw(ArgumentError(lazy"Invalid permutation of length $N: $p")) end @@ -15,10 +17,36 @@ end end # Check whether p is a valid permutation of length N -_isperm(N::Integer, p::AbstractVector) = (length(p) == N && isperm(p)) -_isperm(N::Integer, p::NTuple{M, Integer}) where {M} = (M == N && isperm(p)) +# For N <= 64, the entries are recorded as bits in a mask: N entries that are all in `1:N` form +# a permutation if and only if together they set all N bits. This takes O(N) operations +# without branches or allocations, whereas `Base.isperm` compares all pairs for tuples +# (O(N^2)) and allocates for vectors. For N <= 4, `Base.isperm` is just as fast for tuples. +_isperm(N::Integer, p::NTuple{M, Integer}) where {M} = M == N && _isperm_tuple(p) +_isperm(N::Integer, p::AbstractVector{<:Integer}) = length(p) == N && _isperm_vector(p) +_isperm(N::Integer, p::AbstractVector) = length(p) == N && isperm(p) _isperm(N::Integer, p) = false +@inline function _isperm_tuple(p::NTuple{N, Integer}) where {N} + (N <= 4 || N > 64) && return isperm(p) + return _isperm_mask(p, N) +end +function _isperm_vector(p::AbstractVector{<:Integer}) + length(p) > 64 && return isperm(p) + return _isperm_mask(p, length(p)) +end +@inline function _isperm_mask(p, N::Int) + used = zero(UInt64) + valid = true + for x in p + valid &= (1 <= x <= N) + # `% Int` and `& 63` keep the shift well defined (and branch free) for invalid entries, + # which are rejected through `valid` + used |= one(UInt64) << (((x % Int) - 1) & 63) + end + full = N == 64 ? typemax(UInt64) : (one(UInt64) << N) - one(UInt64) + return valid & (used == full) +end + # Compute the memory index given a list of cartesian indices and corresponding strides @inline function _computeind(indices::NTuple{N, Int}, strides::NTuple{N, Int}) where {N} return (indices[1] - 1) * strides[1] + _computeind(tail(indices), tail(strides)) @@ -126,19 +154,13 @@ _computeviewoffset(::Tuple{}, ::Tuple{}) = 0 # Auxiliary methods for `sreshape` #---------------------------------- # Compute the new strides of a (strided) reshape given the original strides and new and -# original sizes +# original sizes, or `nothing` if the reshape is not possible without copying. +# Callers guarantee that `prod(newsize) == prod(oldsize)`, which is preserved in the +# recursion: once one of the sizes is exhausted, the remaining dimensions of the other one +# all have size 1. _computereshapestrides(newsize::Tuple{}, oldsize::Tuple{}, strides::Tuple{}) = strides -function _computereshapestrides( - newsize::Tuple{}, oldsize::Dims{N}, - strides::Dims{N} - ) where {N} - all(isequal(1), oldsize) || _throw_dimensionmismatch() - return () -end -function _computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{}) - all(isequal(1), newsize) || _throw_dimensionmismatch() - return newsize -end +_computereshapestrides(newsize::Tuple{}, oldsize::Dims, strides::Dims) = () +_computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{}) = newsize function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N}) where {N} d, r = divrem(oldsize[1], newsize[1]) return if r == 0 @@ -156,7 +178,6 @@ function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N return isnothing(stail) ? nothing : (s1, stail...) end else - prod(newsize) == prod(oldsize) || _throw_dimensionmismatch() return nothing end end diff --git a/src/stridedview.jl b/src/stridedview.jl index 4dda54f..30b1d5d 100644 --- a/src/stridedview.jl +++ b/src/stridedview.jl @@ -167,7 +167,8 @@ end end # Indexing with slice indices to create a new view. -function Base.getindex(a::StridedView{T, N}, I::Vararg{SliceIndex, N}) where {T, N} +@inline function Base.getindex(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} + @boundscheck checkbounds(a, I...) newsize = _computeviewsize(a.size, I) newstrides = _normalizestrides(newsize, _computeviewstrides(a.strides, I)) return unsafe_stridedview(a, newsize, newstrides, a.offset + _computeviewoffset(a.strides, I)) @@ -253,18 +254,24 @@ end # Creating or transforming StridedView by slicing #------------------------------------------------- # we cannot use Base.view, as this also accepts indices that might not preserve stridedness -sview(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} = getindex(a, I...) -sview(a::StridedView, I::SliceIndex) = getindex(sreshape(a, (length(a),)), I) +@propagate_inbounds function sview(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} + return getindex(a, I...) +end +@propagate_inbounds function sview(a::StridedView, I::SliceIndex) + return getindex(sreshape(a, (length(a),)), I) +end # for StridedView and index arguments which preserve stridedness, we do replace Base.view # with sview -Base.view(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} = getindex(a, I...) +@propagate_inbounds function Base.view(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} + return getindex(a, I...) +end # `sview` can be used as a constructor when acting on `AbstractArray` objects -function sview(a::AbstractArray{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} +@propagate_inbounds function sview(a::AbstractArray{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} return getindex(StridedView(a), I...) end -function sview(a::AbstractArray, I::SliceIndex) +@propagate_inbounds function sview(a::AbstractArray, I::SliceIndex) return getindex(sreshape(StridedView(a), (length(a),)), I) end @@ -288,8 +295,8 @@ end sreshape(a, args::Vararg{Int}) = sreshape(a, args) function sreshape(a::StridedView, newsize::Dims) size(a) == newsize && return a + prod(newsize) == length(a) || _throw_reshape_dimensionmismatch(size(a), newsize) if any(isequal(0), newsize) - any(isequal(0), size(a)) || _throw_dimensionmismatch() newstrides = one.(newsize) else newstrides = _computereshapestrides(newsize, _simplifydims(size(a), strides(a))...) diff --git a/test/runtests.jl b/test/runtests.jl index dd06f15..d913ada 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -296,6 +296,45 @@ if !is_buildkite @test strides(D) == (1, 0) end + @testset "permutation check" begin + mask(p) = StridedViews._isperm_mask(p, length(p)) + # exhaustive for small lengths, including out of range entries + for N in 0:5, t in Iterators.product(ntuple(_ -> -1:(N + 1), N)...) + @test mask(t) == isperm(t) + @test StridedViews._isperm(N, t) == isperm(t) + @test StridedViews._isperm(N, collect(Int, t)) == isperm(t) + end + for N in (6, 10, 17, 63, 64, 65), _ in 1:50 + p = randperm(N) + @test StridedViews._isperm(N, Tuple(p)) + @test StridedViews._isperm(N, p) + @test StridedViews._isperm(N, UInt8.(p)) + q = copy(p) + q[rand(1:N)] = rand((0, -1, N + 1, typemin(Int), p[mod1(rand(1:N), N)])) + isperm(q) && continue # the replacement can be the original entry + @test !StridedViews._isperm(N, Tuple(q)) + @test !StridedViews._isperm(N, q) + end + @test !StridedViews._isperm(3, (1, 2)) + @test !StridedViews._isperm(2, [1, 2, 3]) + @test !StridedViews._isperm(2, (UInt(2)^63 + 1, 1)) + @test !StridedViews._isperm(2, "ab") + end + + @testset "bounds checks when slicing" begin + A = randn(3, 4, 5) + B = StridedView(A) + @test_throws BoundsError B[1:4, :, :] + @test_throws BoundsError B[0:2, :, 1] + @test_throws BoundsError B[:, 5, :] + @test_throws BoundsError view(B, :, :, 2:6) + @test_throws BoundsError sview(B, :, 1:2:5, 1) + @test_throws BoundsError sview(B, 1:61) + @test_throws BoundsError sview(A, 3:4, :, :) + @test B[3:-1:1, 4:-2:1, 1:0] == A[3:-1:1, 4:-2:1, 1:0] + @test sview(B, 60:-7:1) == vec(A)[60:-7:1] + end + @testset "errors" begin B = StridedView(randn(2, 3, 4)) err = try @@ -308,6 +347,15 @@ if !is_buildkite @test_throws ArgumentError permutedims(B, (1, 2)) @test_throws ArgumentError permutedims(B, [3, 1]) @test_throws DimensionMismatch sreshape(B, (5, 5)) + err = try + sreshape(B, (5, 5)) + catch e + e + end + @test sprint(showerror, err) == + "DimensionMismatch: Cannot reshape a StridedView of size (2, 3, 4) (length 24) to size (5, 5) (length 25)" + @test_throws DimensionMismatch sreshape(StridedView(zeros(2, 0)), (3, 1)) + @test_throws DimensionMismatch sreshape(B, (2, 3, 4, 0)) @test_throws StridedViews.ReshapeException sreshape(B[:, 1:2, :], (2, 8)) @test_throws ArgumentError StridedView(reinterpret(Float32, randn(4))) A = randn(ComplexF64, 4) From e2c88f72c66f21c0f989dffdde62a51a25ea7130 Mon Sep 17 00:00:00 2001 From: Jutho Haegeman Date: Wed, 25 Nov 2026 09:07:54 +0100 Subject: [PATCH 3/3] Fold the tuple and vector permutation checks into `_isperm` Co-Authored-By: Claude Opus 5.5 --- src/auxiliary.jl | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/auxiliary.jl b/src/auxiliary.jl index 0652bf5..776e3e3 100644 --- a/src/auxiliary.jl +++ b/src/auxiliary.jl @@ -21,19 +21,20 @@ end # a permutation if and only if together they set all N bits. This takes O(N) operations # without branches or allocations, whereas `Base.isperm` compares all pairs for tuples # (O(N^2)) and allocates for vectors. For N <= 4, `Base.isperm` is just as fast for tuples. -_isperm(N::Integer, p::NTuple{M, Integer}) where {M} = M == N && _isperm_tuple(p) -_isperm(N::Integer, p::AbstractVector{<:Integer}) = length(p) == N && _isperm_vector(p) +@inline function _isperm(N::Integer, p::NTuple{M, Integer}) where {M} + M == N || return false + # `M` is known at compile time, so only one of the branches remains + (M <= 4 || M > 64) && return isperm(p) + return _isperm_mask(p, M) +end +function _isperm(N::Integer, p::AbstractVector{<:Integer}) + length(p) == N || return false + N > 64 && return isperm(p) + return _isperm_mask(p, Int(N)) +end _isperm(N::Integer, p::AbstractVector) = length(p) == N && isperm(p) _isperm(N::Integer, p) = false -@inline function _isperm_tuple(p::NTuple{N, Integer}) where {N} - (N <= 4 || N > 64) && return isperm(p) - return _isperm_mask(p, N) -end -function _isperm_vector(p::AbstractVector{<:Integer}) - length(p) > 64 && return isperm(p) - return _isperm_mask(p, length(p)) -end @inline function _isperm_mask(p, N::Int) used = zero(UInt64) valid = true