Skip to content

Commit bc0fae2

Browse files
authored
make length(StepRange()) type stable (#45236)
1 parent 5bc1d85 commit bc0fae2

2 files changed

Lines changed: 10 additions & 5 deletions

File tree

base/range.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -762,13 +762,13 @@ let bigints = Union{Int, UInt, Int64, UInt64, Int128, UInt128}
762762
# therefore still be valid (if the result is representable at all)
763763
# n.b. !(s isa T)
764764
if s isa Unsigned || -1 <= s <= 1 || s == -s
765-
a = div(diff, s)
765+
a = div(diff, s) % T
766766
elseif s < 0
767-
a = div(unsigned(-diff), -s) % typeof(diff)
767+
a = div(unsigned(-diff), -s) % T
768768
else
769-
a = div(unsigned(diff), s) % typeof(diff)
769+
a = div(unsigned(diff), s) % T
770770
end
771-
return Integer(a) + oneunit(a)
771+
return a + oneunit(T)
772772
end
773773
function checked_length(r::OrdinalRange{T}) where T<:bigints
774774
s = step(r)
@@ -786,7 +786,7 @@ let bigints = Union{Int, UInt, Int64, UInt64, Int128, UInt128}
786786
else
787787
a = div(checked_sub(start, stop), -s)
788788
end
789-
return checked_add(a, oneunit(a))
789+
return checked_add(convert(T, a), oneunit(T))
790790
end
791791
end
792792

test/ranges.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2031,6 +2031,11 @@ end
20312031
@test typeof(step(r)) === Int8
20322032
end
20332033

2034+
@testset "length(StepRange()) type stability" begin
2035+
typeof(length(StepRange(1,Int128(1),1))) == typeof(length(StepRange(1,Int128(1),0)))
2036+
typeof(checked_length(StepRange(1,Int128(1),1))) == typeof(checked_length(StepRange(1,Int128(1),0)))
2037+
end
2038+
20342039
@testset "LinRange eltype for element types that wrap integers" begin
20352040
struct RealWrapper{T <: Real} <: Real
20362041
x :: T

0 commit comments

Comments
 (0)