Skip to content

Permit the construction of a 1D StepRangeLen of CartesianIndexes #50457

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ module IteratorsMD
CartesianIndex{N}(index::Integer...) where {N} = CartesianIndex{N}(index)
CartesianIndex{N}() where {N} = CartesianIndex{N}(())
# Un-nest passed CartesianIndexes
CartesianIndex{N}(index::CartesianIndex{N}) where {N} = index
CartesianIndex(index::Union{Integer, CartesianIndex}...) = CartesianIndex(flatten(index))
flatten(::Tuple{}) = ()
flatten(I::Tuple{Any}) = Tuple(I[1])
Expand Down Expand Up @@ -166,6 +167,19 @@ module IteratorsMD
Base.iterate(::CartesianIndex) =
error("iteration is deliberately unsupported for CartesianIndex. Use `I` rather than `I...`, or use `Tuple(I)...`")

# ranges are deliberately disabled to prevent ambiguities with the colon constructor
Base.range_start_step_length(start::CartesianIndex, step::CartesianIndex, len::Integer) =
error("range with a specified length is deliberately unsupported for CartesianIndex arguments."*
" Use StepRangeLen($start, $step, $len) to construct this range")

# show is special-cased to avoid the start:stop:step display,
# which constructs a CartesianIndices
# See #50784
function show(io::IO, r::StepRangeLen{<:CartesianIndex})
print(io, "StepRangeLen(", first(r), ", ",
step(r), ", ", length(r), ")")
end

# Iteration
const OrdinalRangeInt = OrdinalRange{Int, Int}
"""
Expand Down
21 changes: 21 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2535,3 +2535,24 @@ end
a = StepRangeLen(1,2,3,2)
@test a[UInt(1)] == -1
end

@testset "StepRangeLen of CartesianIndex-es" begin
CIstart = CartesianIndex(2,3)
CIstep = CartesianIndex(1,1)
r = StepRangeLen(CIstart, CIstep, 4)
@test length(r) == 4
@test first(r) == CIstart
@test step(r) == CIstep
@test last(r) == CartesianIndex(5,6)
@test r[2] == CartesianIndex(3,4)

@test repr(r) == "StepRangeLen($CIstart, $CIstep, 4)"

r = StepRangeLen(CartesianIndex(), CartesianIndex(), 3)
@test all(==(CartesianIndex()), r)
@test length(r) == 3
@test repr(r) == "StepRangeLen(CartesianIndex(), CartesianIndex(), 3)"

errmsg = ("deliberately unsupported for CartesianIndex", "StepRangeLen")
@test_throws errmsg range(CartesianIndex(1), step=CartesianIndex(1), length=3)
end