Skip to content

Commit

Permalink
Cover all implementations of getindex(::AbstractRange,...)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbauman committed Apr 28, 2020
1 parent ac1cc2c commit 40d3bdd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
10 changes: 9 additions & 1 deletion base/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ function view(A::AbstractArray, I::Vararg{Any,N}) where {N}
unsafe_view(_maybe_reshape_parent(A, index_ndims(J...)), J...)
end

# Ranges tend to be compact & immutable
# Ranges implement getindex to return recomputed ranges; use that for views, too (when possible)
function view(r1::OneTo, r2::OneTo)
@_propagate_inbounds_meta
getindex(r1, r2)
Expand All @@ -181,6 +181,14 @@ function view(r1::StepRange, r2::AbstractRange{<:Integer})
@_propagate_inbounds_meta
getindex(r1, r2)
end
function view(r1::StepRangeLen, r2::OrdinalRange{<:Integer})
@_propagate_inbounds_meta
getindex(r1, r2)
end
function view(r1::LinRange, r2::OrdinalRange{<:Integer})
@_propagate_inbounds_meta
getindex(r1, r2)
end

function unsafe_view(A::AbstractArray, I::Vararg{ViewIndex,N}) where {N}
@_inline_meta
Expand Down
9 changes: 9 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1368,6 +1368,15 @@ end
@test view(1:10, 1:5) === 1:5
@test view(1:10, 1:2:5) === 1:2:5
@test view(1:2:9, 1:5) === 1:2:9

# Ensure we don't hit a fallback `view` if there's a better `getindex` implementation
vmt = collect(methods(view, Tuple{AbstractRange, AbstractRange}))
for m in methods(getindex, Tuple{AbstractRange, AbstractRange})
tt = Base.tuple_type_tail(m.sig)
tt == Tuple{AbstractArray,Vararg{Any,N}} where N && continue
vm = findfirst(sig->tt <: Base.tuple_type_tail(sig.sig), vmt)
@test vmt[vm].sig != Tuple{typeof(view),AbstractArray,Vararg{Any,N}} where N
end
end

@testset "Issue #26608" begin
Expand Down

0 comments on commit 40d3bdd

Please sign in to comment.