Skip to content

Commit

Permalink
more efficient array indexing with AbstractUnitRange (JuliaLang#39896)
Browse files Browse the repository at this point in the history
Co-authored-by: Sebastian Stock <[email protected]>
  • Loading branch information
sanjibansg and sostock committed Apr 28, 2021
1 parent ebf6b16 commit bbaca9d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 5 additions & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,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 @@ -844,6 +844,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))

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

@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
end

@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

0 comments on commit bbaca9d

Please sign in to comment.