Skip to content

Commit

Permalink
Specialize CartesianIndices for AbstractUnitRange axes
Browse files Browse the repository at this point in the history
  • Loading branch information
jishnub committed Jul 4, 2021
1 parent 5584620 commit 09252b6
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
5 changes: 5 additions & 0 deletions base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,11 @@ module IteratorsMD
indices = map(r->convert(OrdinalRangeInt, r), inds)
CartesianIndices{N, typeof(indices)}(indices)
end
# specialized method in case conversion to an OrdinalRange is not defined for the indices (see issue #40035)
function CartesianIndices(inds::NTuple{N,AbstractUnitRange{<:Integer}}) where {N}
indices = map(r->convert(AbstractUnitRange{Int}, r), inds)
CartesianIndices{N, typeof(indices)}(indices)
end

CartesianIndices(index::CartesianIndex) = CartesianIndices(index.I)
CartesianIndices(inds::NTuple{N,Union{<:Integer,OrdinalRange{<:Integer}}}) where {N} =
Expand Down
10 changes: 9 additions & 1 deletion test/offsetarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -788,10 +788,18 @@ end
end
end

@testset "proper patition for non-1-indexed vector" begin
@testset "proper partition for non-1-indexed vector" begin
@test Iterators.partition(OffsetArray(1:10,10), 5) |> collect == [1:5,6:10] # OffsetVector
@test Iterators.partition(OffsetArray(collect(1:10),10), 5) |> collect == [1:5,6:10] # OffsetVector
@test Iterators.partition(OffsetArray(reshape(1:9,3,3), (3,3)), 5) |> collect == [1:5,6:9] #OffsetMatrix
@test Iterators.partition(OffsetArray(reshape(collect(1:9),3,3), (3,3)), 5) |> collect == [1:5,6:9] #OffsetMatrix
@test Iterators.partition(IdOffsetRange(2:7,10), 5) |> collect == [12:16,17:17] # IdOffsetRange
end

@testset "CartesianIndices (issue #40035)" begin
A = OffsetArray(big(1):big(2), 0);
B = OffsetArray(1:2, 0);
# axes of an OffsetArray may be converted to an AbstractUnitRange,
# but the conversion to an OrdinalRange is presently not defined.
@test CartesianIndices(A) == CartesianIndices(B)
end
3 changes: 3 additions & 0 deletions test/testhelpers/OffsetArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ function IdOffsetRange{T}(r::IdOffsetRange) where T<:Integer
end
IdOffsetRange(r::IdOffsetRange) = r

AbstractUnitRange{T}(r::IdOffsetRange{T}) where {T} = r
AbstractUnitRange{T}(r::IdOffsetRange) where {T} = IdOffsetRange{T}(r)

# TODO: uncomment these when Julia is ready
# # Conversion preserves both the values and the indexes, throwing an InexactError if this
# # is not possible.
Expand Down

0 comments on commit 09252b6

Please sign in to comment.