Skip to content

Commit 560ede5

Browse files
authored
Permit the construction of a 1D StepRangeLen of CartesianIndexes (JuliaLang#50457)
1 parent e1150db commit 560ede5

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

base/multidimensional.jl

+14
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ module IteratorsMD
8383
CartesianIndex{N}(index::Integer...) where {N} = CartesianIndex{N}(index)
8484
CartesianIndex{N}() where {N} = CartesianIndex{N}(())
8585
# Un-nest passed CartesianIndexes
86+
CartesianIndex{N}(index::CartesianIndex{N}) where {N} = index
8687
CartesianIndex(index::Union{Integer, CartesianIndex}...) = CartesianIndex(flatten(index))
8788
flatten(::Tuple{}) = ()
8889
flatten(I::Tuple{Any}) = Tuple(I[1])
@@ -166,6 +167,19 @@ module IteratorsMD
166167
Base.iterate(::CartesianIndex) =
167168
error("iteration is deliberately unsupported for CartesianIndex. Use `I` rather than `I...`, or use `Tuple(I)...`")
168169

170+
# ranges are deliberately disabled to prevent ambiguities with the colon constructor
171+
Base.range_start_step_length(start::CartesianIndex, step::CartesianIndex, len::Integer) =
172+
error("range with a specified length is deliberately unsupported for CartesianIndex arguments."*
173+
" Use StepRangeLen($start, $step, $len) to construct this range")
174+
175+
# show is special-cased to avoid the start:stop:step display,
176+
# which constructs a CartesianIndices
177+
# See #50784
178+
function show(io::IO, r::StepRangeLen{<:CartesianIndex})
179+
print(io, "StepRangeLen(", first(r), ", ",
180+
step(r), ", ", length(r), ")")
181+
end
182+
169183
# Iteration
170184
const OrdinalRangeInt = OrdinalRange{Int, Int}
171185
"""

test/ranges.jl

+21
Original file line numberDiff line numberDiff line change
@@ -2558,3 +2558,24 @@ end
25582558
a = StepRangeLen(1,2,3,2)
25592559
@test a[UInt(1)] == -1
25602560
end
2561+
2562+
@testset "StepRangeLen of CartesianIndex-es" begin
2563+
CIstart = CartesianIndex(2,3)
2564+
CIstep = CartesianIndex(1,1)
2565+
r = StepRangeLen(CIstart, CIstep, 4)
2566+
@test length(r) == 4
2567+
@test first(r) == CIstart
2568+
@test step(r) == CIstep
2569+
@test last(r) == CartesianIndex(5,6)
2570+
@test r[2] == CartesianIndex(3,4)
2571+
2572+
@test repr(r) == "StepRangeLen($CIstart, $CIstep, 4)"
2573+
2574+
r = StepRangeLen(CartesianIndex(), CartesianIndex(), 3)
2575+
@test all(==(CartesianIndex()), r)
2576+
@test length(r) == 3
2577+
@test repr(r) == "StepRangeLen(CartesianIndex(), CartesianIndex(), 3)"
2578+
2579+
errmsg = ("deliberately unsupported for CartesianIndex", "StepRangeLen")
2580+
@test_throws errmsg range(CartesianIndex(1), step=CartesianIndex(1), length=3)
2581+
end

0 commit comments

Comments
 (0)