Skip to content

Commit

Permalink
Make CartesianRange an AbstractArray
Browse files Browse the repository at this point in the history
  • Loading branch information
barche committed Nov 23, 2017
1 parent 80d8719 commit 4c0d0c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
6 changes: 5 additions & 1 deletion base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ module IteratorsMD
CartesianIndex(2, 2, 2)
```
"""
struct CartesianRange{N,R<:NTuple{N,AbstractUnitRange{Int}}}
struct CartesianRange{N,R<:NTuple{N,AbstractUnitRange{Int}}} <: AbstractArray{CartesianIndex{N},N}
indices::R
end

Expand Down Expand Up @@ -222,6 +222,10 @@ module IteratorsMD
convert(::Type{Tuple{Vararg{UnitRange}}}, R::CartesianRange) =
convert(Tuple{Vararg{UnitRange{Int}}}, R)

# AbstractArray implementation
Base.IndexStyle(::Type{CartesianRange{N,R}}) where {N,R} = IndexCartesian()
@inline Base.getindex(iter::CartesianRange{N,R}, I::Vararg{Int, N}) where {N,R} = CartesianIndex(first.(iter.indices) .- 1 .+ I)

ndims(R::CartesianRange) = ndims(typeof(R))
ndims(::Type{CartesianRange{N}}) where {N} = N
ndims(::Type{CartesianRange{N,TT}}) where {N,TT} = N
Expand Down
18 changes: 18 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -877,3 +877,21 @@ end
Z = Array{Int}(); Z[] = 17
@test Z == collect(Z) == copy(Z)
end

@testset "CartesianRange" begin
xrng = 2:4
yrng = 1:5
CR = CartesianRange((xrng,yrng))

for (i,i_idx) in enumerate(xrng)
for (j,j_idx) in enumerate(yrng)
@test CR[i,j] == CartesianIndex(i_idx,j_idx)
end
end

for i_lin in linearindices(CR)
i = (i_lin-1) % length(xrng) + 1
j = (i_lin-i) ÷ length(xrng) + 1
@test CR[i_lin] == CartesianIndex(xrng[i],yrng[j])
end
end

0 comments on commit 4c0d0c6

Please sign in to comment.