Skip to content

Commit 935dc85

Browse files
mateuszbaranc42f
authored andcommitted
Nested views with static indexing (#657)
This allows StaticIndexing to appear at any position when making a view.
1 parent 98d35ff commit 935dc85

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/indexing.jl

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,4 +369,13 @@ Base.checkindex(B::Type{Bool}, inds::AbstractUnitRange, i::StaticIndexing{T}) wh
369369

370370
# unsafe_view
371371

372-
Base.unsafe_view(A::AbstractArray, i::StaticIndexing{T}) where T = Base.unsafe_view(A, unwrap(i))
372+
# unsafe_view need only deal with vargs of `StaticIndexing`, as wrapped by to_indices.
373+
# i1 is explicitly specified to avoid ambiguities with Base
374+
Base.unsafe_view(A::AbstractArray, i1::StaticIndexing, indices::StaticIndexing...) = Base.unsafe_view(A, unwrap(i1), map(unwrap, indices)...)
375+
376+
# Views of views need a new method for Base.SubArray because storing indices
377+
# wrapped in StaticIndexing in field indices of SubArray causes all sorts of problems.
378+
# Additionally, in some cases the SubArray constructor may be called directly
379+
# instead of unsafe_view so we need this method too (Base._maybe_reindex
380+
# is a good example)
381+
Base.SubArray(A::AbstractArray, indices::NTuple{<:Any,StaticIndexing}) = Base.SubArray(A, map(unwrap, indices))

test/indexing.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,5 +209,18 @@ using StaticArrays, Test
209209
a = collect(11:20)
210210
@test view(a, SVector(1,2,3)) == [11,12,13]
211211
@test_throws BoundsError view(a, SVector(1,11,3))
212+
B = rand(Int,3,4,5,6)
213+
Bv = view(B, 1, (@SVector [2, 1]), [2, 3], (@SVector [4]))
214+
@test Bv == B[1, [2,1], 2:3, [4]]
215+
@test axes(Bv, 1) === SOneTo(2)
216+
@test axes(Bv, 3) === SOneTo(1)
217+
Bvv = view(Bv, (@SVector [1, 2]), 2, 1)
218+
@test axes(Bvv) === (SOneTo(2),)
219+
@test Bvv[1] == B[1, 2, 3, 4]
220+
Bvv[1] = 100
221+
@test Bvv[1] == 100
222+
@test B[1,2,3,4] == 100
223+
@test eltype(Bvv) == Int
224+
@test Bvv[:] == [B[1,2,3,4], B[1,1,3,4]]
212225
end
213226
end

0 commit comments

Comments
 (0)