Skip to content

Commit

Permalink
Make ranges more robust with unsigned indexes.
Browse files Browse the repository at this point in the history
  • Loading branch information
gbaraldi committed Aug 7, 2023
1 parent 9f9e989 commit a8cd1f7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
18 changes: 14 additions & 4 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -963,14 +963,24 @@ end
# This is separate to make it useful even when running with --check-bounds=yes
function unsafe_getindex(r::StepRangeLen{T}, i::Integer) where T
i isa Bool && throw(ArgumentError("invalid index: $i of type Bool"))
u = i - r.offset
T(r.ref + u*r.step)
if i < r.offset # 1 <= offset <= len && 1 <= i <= len
u = r.offset - i
return T(r.ref - u*r.step)
else
u = i - r.offset
return T(r.ref + u*r.step)
end
end

function _getindex_hiprec(r::StepRangeLen, i::Integer) # without rounding by T
i isa Bool && throw(ArgumentError("invalid index: $i of type Bool"))
u = i - r.offset
r.ref + u*r.step
if i < r.offset # 1 <= offset <= len && 1 <= i <= len
u = r.offset - i
return r.ref - u*r.step
else
u = i - r.offset
return r.ref + u*r.step
end
end

function unsafe_getindex(r::LinRange, i::Integer)
Expand Down
12 changes: 10 additions & 2 deletions base/twiceprecision.jl
Original file line number Diff line number Diff line change
Expand Up @@ -478,15 +478,23 @@ function unsafe_getindex(r::StepRangeLen{T,<:TwicePrecision,<:TwicePrecision}, i
# Very similar to _getindex_hiprec, but optimized to avoid a 2nd call to add12
@inline
i isa Bool && throw(ArgumentError("invalid index: $i of type Bool"))
u = i - r.offset
if i < r.offset # 1 <= offset <= len && 1 <= i <= len
u = r.offset - i
else
u = i - r.offset
end
shift_hi, shift_lo = u*r.step.hi, u*r.step.lo
x_hi, x_lo = add12(r.ref.hi, shift_hi)
T(x_hi + (x_lo + (shift_lo + r.ref.lo)))
end

function _getindex_hiprec(r::StepRangeLen{<:Any,<:TwicePrecision,<:TwicePrecision}, i::Integer)
i isa Bool && throw(ArgumentError("invalid index: $i of type Bool"))
u = i - r.offset
if i < r.offset # 1 <= offset <= len && 1 <= i <= len
u = r.offset - i
else
u = i - r.offset
end
shift_hi, shift_lo = u*r.step.hi, u*r.step.lo
x_hi, x_lo = add12(r.ref.hi, shift_hi)
x_hi, x_lo = add12(x_hi, x_lo + (shift_lo + r.ref.lo))
Expand Down
5 changes: 5 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2528,3 +2528,8 @@ end
end

end

@testset "unsigned index #44895" begin
x = range(-1,1,length=11)
x[UInt(1)] == 1.0
end

0 comments on commit a8cd1f7

Please sign in to comment.