Skip to content

Commit 6d42bdd

Browse files
johnnychen94N5N3
authored andcommitted
Eagerly do boundscheck when indexing CartesianIndices with CartesianIndices
1 parent 229c124 commit 6d42bdd

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

base/multidimensional.jl

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -368,14 +368,19 @@ module IteratorsMD
368368
# CartesianIndices act as a multidimensional range, so cartesian indexing of CartesianIndices
369369
# with compatible dimensions may be seen as indexing into the component ranges.
370370
# This may use the special indexing behavior implemented for ranges to return another CartesianIndices
371-
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N,R},
371+
@inline function Base.getindex(iter::CartesianIndices{N,R},
372372
I::Vararg{Union{OrdinalRange{<:Integer, <:Integer}, Colon}, N}) where {N,R}
373-
CartesianIndices(getindex.(iter.indices, I))
373+
@boundscheck checkbounds(iter, I...)
374+
indices = map(iter.indices, I) do r, i
375+
@inbounds getindex(r, i)
376+
end
377+
CartesianIndices(indices)
374378
end
375379
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N},
376380
C::CartesianIndices{N}) where {N}
377-
CartesianIndices(getindex.(iter.indices, C.indices))
381+
getindex(iter, C.indices...)
378382
end
383+
@inline Base.getindex(iter::CartesianIndices{0}, ::CartesianIndices{0}) = iter
379384

380385
# If dimensions permit, we may index into a CartesianIndices directly instead of constructing a SubArray wrapper
381386
@propagate_inbounds function Base.view(c::CartesianIndices{N}, r::Vararg{Union{OrdinalRange{<:Integer, <:Integer}, Colon},N}) where {N}

test/boundscheck_exec.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,7 @@ if bc_opt == bc_default || bc_opt == bc_off
260260
end
261261

262262
@testset "pass inbounds meta to getindex on CartesianIndices (#42115)" begin
263+
@inline getindex_42115(r, i) = @inbounds getindex(r, i)
263264
@inline getindex_42115(r, i, j) = @inbounds getindex(r, i, j)
264265

265266
R = CartesianIndices((5, 5))
@@ -270,6 +271,14 @@ end
270271
@test getindex_42115(R, -1, -1) == CartesianIndex(-1, -1)
271272
@test getindex_42115(R, 1, -1) == CartesianIndex(1, -1)
272273
end
274+
275+
if bc_opt == bc_on
276+
@test_throws BoundsError getindex_42115(R, CartesianIndices((6, 6)))
277+
@test_throws BoundsError getindex_42115(R, -1:3, :)
278+
else
279+
@test getindex_42115(R, CartesianIndices((6, 6))) == CartesianIndices((6, 6))
280+
@test getindex_42115(R, -1:3, :) == CartesianIndices((-1:3, 1:5))
281+
end
273282
end
274283

275284
end

0 commit comments

Comments
 (0)