Skip to content

Commit

Permalink
deleteat!: Handle unassigned array elements (#43941)
Browse files Browse the repository at this point in the history
This function was erroring on unassigned array elements. This is
the minimal fix to resolve that issue. I tried something more
generic, but it turns out all of our Array code basically assumes
that all elements are assigned. Even basic things like `==`, `hash`,
etc. error for arrays with unassigned elements. I think we may want
to strongly consider removing the ability to unassign elements in
arrays in favor of Union{Nothing, T} arrays, which our existing code
handles fine and should be able to be made to have equivalent performance.
  • Loading branch information
Keno committed Jan 27, 2022
1 parent 4650cff commit 5b893dd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
27 changes: 22 additions & 5 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1531,14 +1531,31 @@ deleteat!(a::Vector, inds::AbstractVector) = _deleteat!(a, to_indices(a, (inds,)

struct Nowhere; end
push!(::Nowhere, _) = nothing
_growend!(::Nowhere, _) = nothing

@inline function _push_deleted!(dltd, a::Vector, ind)
if @inbounds isassigned(a, ind)
push!(dltd, @inbounds a[ind])
else
_growend!(dltd, 1)
end
end

@inline function _copy_item!(a::Vector, p, q)
if @inbounds isassigned(a, q)
@inbounds a[p] = a[q]
else
_unsetindex!(a, p)
end
end

function _deleteat!(a::Vector, inds, dltd=Nowhere())
n = length(a)
y = iterate(inds)
y === nothing && return a
(p, s) = y
checkbounds(a, p)
push!(dltd, @inbounds a[p])
_push_deleted!(dltd, a, p)
q = p+1
while true
y = iterate(inds, s)
Expand All @@ -1552,14 +1569,14 @@ function _deleteat!(a::Vector, inds, dltd=Nowhere())
end
end
while q < i
@inbounds a[p] = a[q]
_copy_item!(a, p, q)
p += 1; q += 1
end
push!(dltd, @inbounds a[i])
_push_deleted!(dltd, a, i)
q = i+1
end
while q <= n
@inbounds a[p] = a[q]
_copy_item!(a, p, q)
p += 1; q += 1
end
_deleteend!(a, n-p+1)
Expand All @@ -1572,7 +1589,7 @@ function deleteat!(a::Vector, inds::AbstractVector{Bool})
length(inds) == n || throw(BoundsError(a, inds))
p = 1
for (q, i) in enumerate(inds)
@inbounds a[p] = a[q]
_copy_item!(a, p, q)
p += !i
end
_deleteend!(a, n-p+1)
Expand Down
5 changes: 5 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1516,6 +1516,11 @@ end
@test_throws BoundsError deleteat!([], [2])
@test deleteat!([], []) == []
@test deleteat!([], Bool[]) == []
let a = Vector{Any}(undef, 2)
a[1] = 1
@test isassigned(deleteat!(copy(a), [2]), 1)
@test !isassigned(deleteat!(copy(a), [1]), 1)
end
end

@testset "comprehensions" begin
Expand Down

0 comments on commit 5b893dd

Please sign in to comment.