Skip to content

Commit dc26322

Browse files
authored
fix overflow for empty non-integer-type ranges (#43043)
Fixes #29810
1 parent d08b05d commit dc26322

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

base/range.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -360,8 +360,8 @@ function steprange_last_empty(start::Integer, step, stop)
360360
end
361361
last
362362
end
363-
# For types where x+oneunit(x) may not be well-defined
364-
steprange_last_empty(start, step, stop) = start - step
363+
# For types where x+oneunit(x) may not be well-defined use the user-given value for stop
364+
steprange_last_empty(start, step, stop) = stop
365365

366366
StepRange{T}(start, step::S, stop) where {T,S} = StepRange{T,S}(start, step, stop)
367367
StepRange(start::T, step::S, stop::T) where {T,S} = StepRange{T,S}(start, step, stop)
@@ -692,7 +692,7 @@ function checked_length(r::OrdinalRange{T}) where T
692692
# s != 0, by construction, but avoids the division error later
693693
start = first(r)
694694
if s == zero(s) || isempty(r)
695-
return Integer(start - start + zero(s))
695+
return Integer(div(start - start, oneunit(s)))
696696
end
697697
stop = last(r)
698698
if isless(s, zero(s))
@@ -719,7 +719,7 @@ function length(r::OrdinalRange{T}) where T
719719
# s != 0, by construction, but avoids the division error later
720720
start = first(r)
721721
if s == zero(s) || isempty(r)
722-
return Integer(div(start-start, oneunit(s)))
722+
return Integer(div(start - start, oneunit(s)))
723723
end
724724
stop = last(r)
725725
if isless(s, zero(s))
@@ -811,7 +811,7 @@ first(r::OneTo{T}) where {T} = oneunit(T)
811811
first(r::StepRangeLen) = unsafe_getindex(r, 1)
812812
first(r::LinRange) = r.start
813813

814-
last(r::OrdinalRange{T}) where {T} = convert(T, r.stop)
814+
last(r::OrdinalRange{T}) where {T} = convert(T, r.stop) # via steprange_last
815815
last(r::StepRangeLen) = unsafe_getindex(r, length(r))
816816
last(r::LinRange) = r.stop
817817

test/ranges.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2210,3 +2210,13 @@ end
22102210
@test iszero(length(Fix42528(0x1):Fix42528(0x0)))
22112211
@test_throws DomainError Fix42528(0x0) - Fix42528(0x1)
22122212
end
2213+
2214+
let r = Ptr{Cvoid}(20):-UInt(2):Ptr{Cvoid}(10)
2215+
@test isempty(r)
2216+
@test length(r) == 0
2217+
@test count(i -> true, r) == 0
2218+
@test isempty(collect(r))
2219+
@test first(r) === Ptr{Cvoid}(20)
2220+
@test step(r) === -UInt(2)
2221+
@test last(r) === Ptr{Cvoid}(10)
2222+
end

0 commit comments

Comments
 (0)