Skip to content

Commit

Permalink
fix overflow for empty non-integer-type ranges
Browse files Browse the repository at this point in the history
Fixes #29810
  • Loading branch information
vtjnash committed Nov 11, 2021
1 parent c25b704 commit 97ca94b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
10 changes: 5 additions & 5 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,8 @@ function steprange_last_empty(start::Integer, step, stop)
end
last
end
# For types where x+oneunit(x) may not be well-defined
steprange_last_empty(start, step, stop) = start - step
# For types where x+oneunit(x) may not be well-defined use the user-given value for stop
steprange_last_empty(start, step, stop) = stop

StepRange{T}(start, step::S, stop) where {T,S} = StepRange{T,S}(start, step, stop)
StepRange(start::T, step::S, stop::T) where {T,S} = StepRange{T,S}(start, step, stop)
Expand Down Expand Up @@ -692,7 +692,7 @@ function checked_length(r::OrdinalRange{T}) where T
# s != 0, by construction, but avoids the division error later
start = first(r)
if s == zero(s) || isempty(r)
return Integer(start - start + zero(s))
return Integer(div(start - start, oneunit(s)))
end
stop = last(r)
if isless(s, zero(s))
Expand All @@ -719,7 +719,7 @@ function length(r::OrdinalRange{T}) where T
# s != 0, by construction, but avoids the division error later
start = first(r)
if s == zero(s) || isempty(r)
return Integer(div(start-start, oneunit(s)))
return Integer(div(start - start, oneunit(s)))
end
stop = last(r)
if isless(s, zero(s))
Expand Down Expand Up @@ -811,7 +811,7 @@ first(r::OneTo{T}) where {T} = oneunit(T)
first(r::StepRangeLen) = unsafe_getindex(r, 1)
first(r::LinRange) = r.start

last(r::OrdinalRange{T}) where {T} = convert(T, r.stop)
last(r::OrdinalRange{T}) where {T} = convert(T, r.stop) # via steprange_last
last(r::StepRangeLen) = unsafe_getindex(r, length(r))
last(r::LinRange) = r.stop

Expand Down
10 changes: 10 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2210,3 +2210,13 @@ end
@test iszero(length(Fix42528(0x1):Fix42528(0x0)))
@test_throws DomainError Fix42528(0x0) - Fix42528(0x1)
end

let r = Ptr{Cvoid}(20):-UInt(2):Ptr{Cvoid}(10)
@test isempty(r)
@test length(r) == 0
@test count(i -> true, r) == 0
@test isempty(collect(r))
@test first(r) === Ptr{Cvoid}(20)
@test step(r) === -UInt(2)
@test last(r) === Ptr{Cvoid}(10)
end

0 comments on commit 97ca94b

Please sign in to comment.