Skip to content

Commit b71330d

Browse files
authored
ranges: fix empty length for smallints (#43042)
Fixes #29801
1 parent dc26322 commit b71330d

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

base/range.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -798,7 +798,12 @@ let smallints = (Int === Int64 ?
798798
Union{Int8, UInt8, Int16, UInt16})
799799
global length, checked_length
800800
# n.b. !(step isa T)
801-
length(r::OrdinalRange{<:smallints}) = div(Int(last(r)) - Int(first(r)), step(r)) + 1
801+
function length(r::OrdinalRange{<:smallints})
802+
s = step(r)
803+
s == zero(s) && return 0 # unreachable, by construction, but avoids the error case here later
804+
isempty(r) && return 0
805+
return div(Int(last(r)) - Int(first(r)), s) + 1
806+
end
802807
length(r::AbstractUnitRange{<:smallints}) = Int(last(r)) - Int(first(r)) + 1
803808
length(r::OneTo{<:smallints}) = Int(r.stop)
804809
checked_length(r::OrdinalRange{<:smallints}) = length(r)

test/ranges.jl

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,13 +1049,19 @@ end
10491049
@test length(map(identity, UInt64(1):UInt64(5))) == 5
10501050
@test length(map(identity, UInt128(1):UInt128(5))) == 5
10511051
end
1052-
@testset "issue #8531" begin
1052+
@testset "issue #8531, issue #29801" begin
10531053
smallint = (Int === Int64 ?
1054-
(Int8,UInt8,Int16,UInt16,Int32,UInt32) :
1055-
(Int8,UInt8,Int16,UInt16))
1054+
(Int8, UInt8, Int16, UInt16, Int32, UInt32) :
1055+
(Int8, UInt8, Int16, UInt16))
10561056
for T in smallint
10571057
s = typemin(T):typemax(T)
1058-
@test length(s) == checked_length(s) == 2^(8*sizeof(T))
1058+
@test length(s) === checked_length(s) === 2^(8*sizeof(T))
1059+
s = T(10):typemax(T):T(10)
1060+
@test length(s) === checked_length(s) === 1
1061+
s = T(10):typemax(T):T(0)
1062+
@test length(s) === checked_length(s) === 0
1063+
s = T(10):typemax(T):typemin(T)
1064+
@test length(s) === checked_length(s) === 0
10591065
end
10601066
end
10611067

0 commit comments

Comments
 (0)