Skip to content

Commit 41353d2

Browse files
fix: fix n-dimensional view into n-dimensional SArray with Any eltype (#1310)
As of the latest release, trying to `view` into an `SArray` with an eltype of `Any` such that the view also returns an `SArray` would wrap the returned array in a scalar. `_maybewrapscalar` assumes that if the `eltype` of the array matches the type of the view, it must be a scalar view. This assumption breaks down when the `eltype` is `Any`. MWE: ```julia julia> A = SVector{4, Any}(1,2,3,4) julia> I = SVector{2}(3, 1) julia> view(A, I) Scalar{Any}((Any[3, 1],)) julia> view(A, [3, 1]) 2-element view(::SVector{4, Any}, [3, 1]) with eltype Any: 3 1 ``` I've verified that all the added tests fail on the latest release and pass with this PR.
1 parent 563adeb commit 41353d2

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/abstractarray.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -285,11 +285,11 @@ end
285285
# SArrays may avoid the SubArray wrapper and consequently an additional level of indirection
286286
# The output may use the broadcasting machinery defined for StaticArrays (see issue #892)
287287
# wrap elements in Scalar to be consistent with 0D views
288-
_maybewrapscalar(S::SArray{<:Any,T}, r::T) where {T} = Scalar{T}(r)
289-
_maybewrapscalar(S, r) = r
288+
_maybewrapscalar(::Tuple{}, r::T) where {T} = Scalar{T}(r)
289+
_maybewrapscalar(_, r) = r
290290
function Base.view(S::SArray, I::Union{Colon, Integer, SOneTo, StaticArray{<:Tuple, Int}, CartesianIndex}...)
291291
V = getindex(S, I...)
292-
_maybewrapscalar(S, V)
292+
_maybewrapscalar(Base.index_dimsum(I...), V)
293293
end
294294

295295
# zeros, ones and fill may return SArrays if all the axes are statically sized

test/indexing.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,4 +253,16 @@ using StaticArrays, Test
253253
@test lastindex(ind[3]) === 2
254254
@test size(ind[3]) === (2,)
255255
end
256+
257+
@testset "Array view into `Any` eltype `SArray`" begin
258+
A = SVector{4, Any}(1,2,3,4)
259+
v = @inferred view(A, SA[3, 1])
260+
@test v == SVector{2, Any}(3, 1)
261+
A = SMatrix{2, 2, Any}(1, 2, 3, 4)
262+
v = @inferred view(A, @SArray(fill(1, 1, 1)))
263+
@test v == SMatrix{1, 1, Any}(1)
264+
A = SArray{Tuple{2, 2, 2}, Any}(1, 2, 3, 4, 5, 6, 7, 8)
265+
v = @inferred view(A, @SArray(fill(1, 1, 1, 1)))
266+
@test v == SArray{Tuple{1, 1, 1}, Any}(1)
267+
end
256268
end

0 commit comments

Comments
 (0)