Skip to content

Commit

Permalink
Make view of range with range be a range
Browse files Browse the repository at this point in the history
Typical `AbstractRange` types are compact and immutable, and we can
remove the overhead of `SubArray` in this case while the cost of `view`
remains O(1).

Here we specialize only on valid combinations of integer ranges,
otherwise still relying on `SubArray`.
  • Loading branch information
Andy Ferris committed May 17, 2018
1 parent d44944d commit f49cee2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
18 changes: 18 additions & 0 deletions base/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,24 @@ 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
function view(r1::OneTo, r2::OneTo)
@_propagate_inbounds_meta
getindex(r1, r2)
end
function view(r1::AbstractUnitRange, r2::AbstractUnitRange{<:Integer})
@_propagate_inbounds_meta
getindex(r1, r2)
end
function view(r1::AbstractUnitRange, r2::StepRange{<:Integer})
@_propagate_inbounds_meta
getindex(r1, r2)
end
function view(r1::StepRange, r2::AbstractRange{<:Integer})
@_propagate_inbounds_meta
getindex(r1, r2)
end

function unsafe_view(A::AbstractArray, I::Vararg{ViewIndex,N}) where {N}
@_inline_meta
SubArray(A, I)
Expand Down
7 changes: 7 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1263,3 +1263,10 @@ end
@test step(x) == 0.0
@test x isa StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}
end

@testset "Views of ranges" begin
@test view(Base.OneTo(10), Base.OneTo(5)) === Base.OneTo(5)
@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
end

0 comments on commit f49cee2

Please sign in to comment.