Skip to content

Commit

Permalink
ranges: fix empty length for smallints (JuliaLang#43042)
Browse files Browse the repository at this point in the history
Fixes JuliaLang#29801

(cherry picked from commit b71330d)
  • Loading branch information
vtjnash authored and daviehh committed Nov 16, 2021
1 parent c5206aa commit 03d9390
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
7 changes: 6 additions & 1 deletion base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,12 @@ let smallints = (Int === Int64 ?
Union{Int8, UInt8, Int16, UInt16})
global length, checked_length
# n.b. !(step isa T)
length(r::OrdinalRange{<:smallints}) = div(Int(last(r)) - Int(first(r)), step(r)) + 1
function length(r::OrdinalRange{<:smallints})
s = step(r)
s == zero(s) && return 0 # unreachable, by construction, but avoids the error case here later
isempty(r) && return 0
return div(Int(last(r)) - Int(first(r)), s) + 1
end
length(r::AbstractUnitRange{<:smallints}) = Int(last(r)) - Int(first(r)) + 1
length(r::OneTo{<:smallints}) = Int(r.stop)
checked_length(r::OrdinalRange{<:smallints}) = length(r)
Expand Down
14 changes: 10 additions & 4 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1014,13 +1014,19 @@ end
@test length(map(identity, UInt64(1):UInt64(5))) == 5
@test length(map(identity, UInt128(1):UInt128(5))) == 5
end
@testset "issue #8531" begin
@testset "issue #8531, issue #29801" begin
smallint = (Int === Int64 ?
(Int8,UInt8,Int16,UInt16,Int32,UInt32) :
(Int8,UInt8,Int16,UInt16))
(Int8, UInt8, Int16, UInt16, Int32, UInt32) :
(Int8, UInt8, Int16, UInt16))
for T in smallint
s = typemin(T):typemax(T)
@test length(s) == checked_length(s) == 2^(8*sizeof(T))
@test length(s) === checked_length(s) === 2^(8*sizeof(T))
s = T(10):typemax(T):T(10)
@test length(s) === checked_length(s) === 1
s = T(10):typemax(T):T(0)
@test length(s) === checked_length(s) === 0
s = T(10):typemax(T):typemin(T)
@test length(s) === checked_length(s) === 0
end
end

Expand Down

0 comments on commit 03d9390

Please sign in to comment.