Skip to content

Commit

Permalink
Fix conversion in getindex (JuliaLang#26615)
Browse files Browse the repository at this point in the history
* Test more out of bounds errors for the UnitRange type

* Do the conversion in getindex of UnitRange only when returning
  • Loading branch information
haampie authored and KristofferC committed Jun 26, 2018
1 parent 4e3902d commit c500caa
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
18 changes: 15 additions & 3 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -478,11 +478,23 @@ end

## indexing

_in_unit_range(v::UnitRange, val, i::Integer) = i > 0 && val <= v.stop && val >= v.start

function getindex(v::UnitRange{T}, i::Integer) where T
@_inline_meta
ret = convert(T, first(v) + i - 1)
@boundscheck ((i > 0) & (ret <= v.stop) & (ret >= v.start)) || throw_boundserror(v, i)
ret
val = convert(T, v.start + i - 1)
@boundscheck _in_unit_range(v, val, i) || throw_boundserror(v, i)
val
end

const OverflowSafe = Union{Bool,Int8,Int16,Int32,Int64,Int128,
UInt8,UInt16,UInt32,UInt64,UInt128}

function getindex(v::UnitRange{T}, i::Integer) where {T<:OverflowSafe}
@_inline_meta
val = v.start + i - 1
@boundscheck _in_unit_range(v, val, i) || throw_boundserror(v, i)
val % T
end

function getindex(v::OneTo{T}, i::Integer) where T
Expand Down
6 changes: 6 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1286,6 +1286,12 @@ end
@test x isa StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}
end

@testset "Issue #26608" begin
@test_throws BoundsError (Int8(-100):Int8(100))[400]
@test_throws BoundsError (-100:100)[typemax(UInt)]
@test_throws BoundsError (false:true)[3]
end

module NonStandardIntegerRangeTest

using Test
Expand Down

0 comments on commit c500caa

Please sign in to comment.