Skip to content

Commit 99548f2

Browse files
committed
Make CartesianRange an AbstractArray
1 parent 80d8719 commit 99548f2

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

base/multidimensional.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ module IteratorsMD
185185
CartesianIndex(2, 2, 2)
186186
```
187187
"""
188-
struct CartesianRange{N,R<:NTuple{N,AbstractUnitRange{Int}}}
188+
struct CartesianRange{N,R<:NTuple{N,AbstractUnitRange{Int}}} <: AbstractArray{CartesianIndex{N},N}
189189
indices::R
190190
end
191191

@@ -222,6 +222,10 @@ module IteratorsMD
222222
convert(::Type{Tuple{Vararg{UnitRange}}}, R::CartesianRange) =
223223
convert(Tuple{Vararg{UnitRange{Int}}}, R)
224224

225+
# AbstractArray implementation
226+
Base.IndexStyle(::Type{CartesianRange{N,R}}) where {N,R} = IndexCartesian()
227+
@inline Base.getindex(iter::CartesianRange{N,R}, I::Vararg{Int, N}) where {N,R} = CartesianIndex(first.(iter.indices) .- 1) + CartesianIndex(I)
228+
225229
ndims(R::CartesianRange) = ndims(typeof(R))
226230
ndims(::Type{CartesianRange{N}}) where {N} = N
227231
ndims(::Type{CartesianRange{N,TT}}) where {N,TT} = N

test/abstractarray.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,3 +877,21 @@ end
877877
Z = Array{Int}(); Z[] = 17
878878
@test Z == collect(Z) == copy(Z)
879879
end
880+
881+
@testset "CartesianRange" begin
882+
xrng = 2:4
883+
yrng = 1:5
884+
CR = CartesianRange((xrng,yrng))
885+
886+
for (i,i_idx) in enumerate(xrng)
887+
for (j,j_idx) in enumerate(yrng)
888+
@test CR[i,j] == CartesianIndex(i_idx,j_idx)
889+
end
890+
end
891+
892+
for i_lin in linearindices(CR)
893+
i = (i_lin-1) % length(xrng) + 1
894+
j = (i_lin-i) ÷ length(xrng) + 1
895+
@test CR[i_lin] == CartesianIndex(xrng[i],yrng[j])
896+
end
897+
end

0 commit comments

Comments
 (0)