Skip to content

Commit

Permalink
fix vector indexing for offset ranges (JuliaLang#41213)
Browse files Browse the repository at this point in the history
  • Loading branch information
jishnub authored Jul 19, 2021
1 parent e4a6f1d commit 6182eef
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,7 @@ function getindex(r::AbstractUnitRange, s::AbstractUnitRange{T}) where {T<:Integ
range(first(s) ? first(r) : last(r), length = Int(last(s)))
else
f = first(r)
st = oftype(f, f + first(s)-1)
st = oftype(f, f + first(s)-firstindex(r))
return range(st, length=length(s))
end
end
Expand All @@ -918,7 +918,7 @@ function getindex(r::AbstractUnitRange, s::StepRange{T}) where {T<:Integer}
if T === Bool
range(first(s) ? first(r) : last(r), step=oneunit(eltype(r)), length = Int(last(s)))
else
st = oftype(first(r), first(r) + s.start-1)
st = oftype(first(r), first(r) + s.start-firstindex(r))
return range(st, step=step(s), length=length(s))
end
end
Expand Down
28 changes: 28 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2046,3 +2046,31 @@ end
@test_throws BoundsError r[Base.IdentityUnitRange(-1:100)]
end
end

@testset "non 1-based ranges indexing" begin
struct ZeroBasedUnitRange{T,A<:AbstractUnitRange{T}} <: AbstractUnitRange{T}
a :: A
function ZeroBasedUnitRange(a::AbstractUnitRange{T}) where {T}
@assert !Base.has_offset_axes(a)
new{T, typeof(a)}(a)
end
end

Base.parent(A::ZeroBasedUnitRange) = A.a
Base.first(A::ZeroBasedUnitRange) = first(parent(A))
Base.length(A::ZeroBasedUnitRange) = length(parent(A))
Base.last(A::ZeroBasedUnitRange) = last(parent(A))
Base.size(A::ZeroBasedUnitRange) = size(parent(A))
Base.axes(A::ZeroBasedUnitRange) = map(x -> Base.IdentityUnitRange(0:x-1), size(parent(A)))
Base.getindex(A::ZeroBasedUnitRange, i::Int) = parent(A)[i + 1]
Base.getindex(A::ZeroBasedUnitRange, i::Integer) = parent(A)[i + 1]
Base.firstindex(A::ZeroBasedUnitRange) = 0
function Base.show(io::IO, A::ZeroBasedUnitRange)
show(io, parent(A))
print(io, " with indices $(axes(A,1))")
end

r = ZeroBasedUnitRange(5:8)
@test r[0:2] == r[0]:r[2]
@test r[0:1:2] == r[0]:1:r[2]
end

0 comments on commit 6182eef

Please sign in to comment.