Skip to content

Commit

Permalink
avoid potential under/overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
vchuravy committed Mar 16, 2019
1 parent 447de54 commit 807a0c8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
30 changes: 20 additions & 10 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1604,10 +1604,11 @@ CartesianIndex(2, 1)
function findnext(A, start)
l = last(keys(A))
i = start
while i <= l
if A[i]
return i
end
i > l && return nothing
while true
A[i] && return i
i == l && break
# nextind(A, l) can throw/overflow
i = nextind(A, i)
end
return nothing
Expand Down Expand Up @@ -1685,10 +1686,11 @@ CartesianIndex(1, 1)
function findnext(testf::Function, A, start)
l = last(keys(A))
i = start
while i <= l
if testf(A[i])
return i
end
i > l && return nothing
while true
testf(A[i]) && return i
i == l && break
# nextind(A, l) can throw/overflow
i = nextind(A, i)
end
return nothing
Expand Down Expand Up @@ -1781,8 +1783,12 @@ CartesianIndex(2, 1)
"""
function findprev(A, start)
i = start
while i >= first(keys(A))
f = first(keys(A))
i < f && return nothing
while true
A[i] && return i
i == f && break
# prevind(A, l) can throw/underflow
i = prevind(A, i)
end
return nothing
Expand Down Expand Up @@ -1868,8 +1874,12 @@ CartesianIndex(2, 1)
"""
function findprev(testf::Function, A, start)
i = start
while i >= first(keys(A))
f = first(keys(A))
i < f && return nothing
while true
testf(A[i]) && return i
i == f && break
# prevind(A, l) can throw/underflow
i = prevind(A, i)
end
return nothing
Expand Down
14 changes: 10 additions & 4 deletions base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,19 @@ module IteratorsMD
# nextind and prevind with CartesianIndex
function Base.nextind(a::AbstractArray{<:Any,N}, i::CartesianIndex{N}) where {N}
iter = CartesianIndices(axes(a))
_, I = inc((), i.I, first(iter).I, last(iter).I)
return I
I = inc((), i.I, first(iter).I, last(iter).I)
if I === nothing
throw(BoundsError(a, i))
else
return I[2]
end
function Base.prevind(a::AbstractArray{<:Any,N}, i::CartesianIndex{N}) where {N}
iter = CartesianIndices(axes(a))
_, I = dec((), i.I, first(iter).I, last(iter).I)
return I
I = dec((), i.I, first(iter).I, last(iter).I)
if I === nothing
throw(BoundsError(a, i))
else
return I[2]
end

# Iteration over the elements of CartesianIndex cannot be supported until its length can be inferred,
Expand Down

0 comments on commit 807a0c8

Please sign in to comment.