Skip to content

Commit c53a671

Browse files
committed
Support indexing with reshape
1 parent 2aad1f1 commit c53a671

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/indexing.jl

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,12 +230,14 @@ end
230230
# getindex
231231

232232
@propagate_inbounds function getindex(a::StaticArray, inds::Union{Int, StaticArray{<:Tuple, Int}, SOneTo, Colon}...)
233-
_getindex(a, index_sizes(Size(a), inds...), inds)
233+
ar = reshape(a, Val(length(inds)))
234+
_getindex(ar, index_sizes(Size(ar), inds...), inds)
234235
end
235236

236237
if isdefined(Base, :IdentityUnitRange)
237238
@propagate_inbounds function getindex(a::StaticArray, inds::Union{Int, StaticArray{<:Tuple, Int}, SOneTo, Colon, Base.IdentityUnitRange{<:SOneTo}}...)
238-
_getindex(a, index_sizes(Size(a), inds...), inds)
239+
ar = reshape(a, Val(length(inds)))
240+
_getindex(ar, index_sizes(Size(ar), inds...), inds)
239241
end
240242
end
241243

test/indexing.jl

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,12 @@ using StaticArrays, Test
137137
@test v[2,1] == 2
138138
@test_throws BoundsError v[1,2]
139139
@test_throws BoundsError v[3,1]
140+
141+
# SOneTo
142+
@test (@inferred v[axes(v,1), SOneTo(1)]) === SMatrix{2,1}(v)
143+
@test v[axes(v,1), SOneTo(1)] == v[Base.OneTo(length(v)), Base.OneTo(1)]
144+
@test (@inferred v[axes(v,1), 1, SOneTo(1)]) === SMatrix{2,1}(v)
145+
@test v[axes(v,1), 1, SOneTo(1)] == v[Base.OneTo(length(v)), 1, Base.OneTo(1)]
140146
end
141147

142148
@testset "2D getindex() on SMatrix" begin
@@ -249,6 +255,29 @@ using StaticArrays, Test
249255
@test (@inferred getindex(a, SVector(1,2), 1, 1, 1)) == [24,48]
250256
end
251257

258+
@testset "indexing with reshape for SMatrix/MMatrix" begin
259+
sm = @SMatrix [1 3; 2 4]
260+
mm = @MMatrix [1 3; 2 4]
261+
for m in Any[sm, mm, view(sm, :, :), view(mm, :, :)]
262+
sa = @inferred m[:, SOneTo(1), 1, SOneTo(1)]
263+
a = m[:, Base.OneTo(1), 1, Base.OneTo(1)]
264+
@test sa == a
265+
@test sa == SArray{Tuple{2,1,1}}(a)
266+
if m isa SArray
267+
@test sa === SArray{Tuple{2,1,1}}(a)
268+
end
269+
270+
if isdefined(Base, :IdentityUnitRange)
271+
sa = @inferred m[:, Base.IdentityUnitRange(SOneTo(1)), 1, SOneTo(1)]
272+
@test sa == a
273+
@test sa == SArray{Tuple{2,1,1}}(a)
274+
if m isa SArray
275+
@test sa === SArray{Tuple{2,1,1}}(a)
276+
end
277+
end
278+
end
279+
end
280+
252281
@testset "Indexing with empty vectors" begin
253282
a = [1.0 2.0; 3.0 4.0]
254283
@test a[SVector{0,Int}()] == SVector{0,Float64}(())

0 commit comments

Comments
 (0)