Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

more efficient array indexing with AbstractUnitRange #39896

Merged
merged 21 commits into from
Apr 28, 2021
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ function getindex end
@eval getindex(A::Array, i1::Int, i2::Int, I::Int...) = (@_inline_meta; arrayref($(Expr(:boundscheck)), A, i1, i2, I...))

# Faster contiguous indexing using copyto! for UnitRange and Colon
function getindex(A::Array, I::UnitRange{Int})
function getindex(A::Array, I::AbstractUnitRange{<:Integer})
@_inline_meta
@boundscheck checkbounds(A, I)
lI = length(I)
Expand All @@ -813,6 +813,10 @@ function getindex(A::Array, I::UnitRange{Int})
end
return X
end

# getindex for carrying out logical indexing for AbstractUnitRange{Bool} as Bool <: Integer
getindex(a::Array, r::AbstractUnitRange{Bool}) = getindex(a, to_index(r))
sanjibansg marked this conversation as resolved.
Show resolved Hide resolved

function getindex(A::Array, c::Colon)
lI = length(A)
X = similar(A, lI)
Expand Down
18 changes: 18 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1293,6 +1293,24 @@ end
@test_throws ArgumentError Int[t...; 3 4 5]
end


sanjibansg marked this conversation as resolved.
Show resolved Hide resolved
@testset "issue #39896, modified getindex " begin
for arr = ([1:10;], reshape([1.0:16.0;],4,4), reshape(['a':'h';],2,2,2))
for inds = (2:5, Base.OneTo(5), BigInt(3):BigInt(5), UInt(4):UInt(3))
@test arr[inds] == arr[collect(inds)]
@test arr[inds] isa AbstractVector{eltype(arr)}
end
end
for arr = ([1], reshape([1.0],1,1), reshape(['a'],1,1,1))
@test arr[true:true] == [arr[1]]
@test arr[true:true] isa AbstractVector{eltype(arr)}
@test arr[false:false] == []
@test arr[false:false] isa AbstractVector{eltype(arr)}
end
for arr = ([1:10;], reshape([1.0:16.0;],4,4), reshape(['a':'h';],2,2,2))
@test_throws BoundsError arr[true:true]
@test_throws BoundsError arr[false:false]
end
sanjibansg marked this conversation as resolved.
Show resolved Hide resolved
@testset "reduce(vcat, ...) inferrence #40277" begin
x_vecs = ([5, ], [1.0, 2.0, 3.0])
@test @inferred(reduce(vcat, x_vecs)) == [5.0, 1.0, 2.0, 3.0]
Expand Down