Skip to content

Commit

Permalink
Fix linear indexing of one-dimensional CartesianIndices (#28401)
Browse files Browse the repository at this point in the history
The distinction between the values and the axes can be tricky
  • Loading branch information
timholy authored and StefanKarpinski committed Aug 2, 2018
1 parent 3b50b2d commit 2c08695
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
6 changes: 3 additions & 3 deletions base/indices.jl
Original file line number Diff line number Diff line change
Expand Up @@ -390,11 +390,11 @@ function getindex(iter::LinearIndices, i::AbstractRange{<:Integer})
end
# More efficient iteration — predominantly for non-vector LinearIndices
# but one-dimensional LinearIndices must be special-cased to support OffsetArrays
iterate(iter::LinearIndices{1}, s...) = iterate(iter.indices[1], s...)
iterate(iter::LinearIndices{1}, s...) = iterate(axes1(iter.indices[1]), s...)
iterate(iter::LinearIndices, i=1) = i > length(iter) ? nothing : (i, i+1)

# Needed since firstindex and lastindex are defined in terms of LinearIndices
first(iter::LinearIndices) = 1
first(iter::LinearIndices{1}) = (@_inline_meta; first(iter.indices[1]))
first(iter::LinearIndices{1}) = (@_inline_meta; first(axes1(iter.indices[1])))
last(iter::LinearIndices) = (@_inline_meta; length(iter))
last(iter::LinearIndices{1}) = (@_inline_meta; last(iter.indices[1]))
last(iter::LinearIndices{1}) = (@_inline_meta; last(axes1(iter.indices[1])))
11 changes: 11 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,17 @@ end
# indices may be nontraditional
@test_throws ArgumentError Base._sub2ind((1:3,), 2)
@test_throws ArgumentError Base._ind2sub((1:3,), 2)

ci = CartesianIndices((2:4,))
@test first(ci) == ci[1] == CartesianIndex(2)
@test last(ci) == ci[end] == ci[3] == CartesianIndex(4)
li = LinearIndices(ci)
@test collect(li) == [1,2,3]
@test first(li) == li[1] == 1
@test last(li) == li[3] == 3
io = IOBuffer()
show(io, ci)
@test String(take!(io)) == "CartesianIndex{1}[CartesianIndex(2,), CartesianIndex(3,), CartesianIndex(4,)]"
end

@testset "2-dimensional" begin
Expand Down

0 comments on commit 2c08695

Please sign in to comment.