Skip to content

Commit fc5b905

Browse files
committed
Eagerly do boundscheck when indexing CartesianIndices with CartesianIndices
1 parent ace60cf commit fc5b905

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
@@ -370,14 +370,19 @@ module IteratorsMD
370370
# CartesianIndices act as a multidimensional range, so cartesian indexing of CartesianIndices
371371
# with compatible dimensions may be seen as indexing into the component ranges.
372372
# This may use the special indexing behavior implemented for ranges to return another CartesianIndices
373-
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N,R},
373+
@inline function Base.getindex(iter::CartesianIndices{N,R},
374374
I::Vararg{Union{OrdinalRange{<:Integer, <:Integer}, Colon}, N}) where {N,R}
375-
CartesianIndices(getindex.(iter.indices, I))
375+
@boundscheck checkbounds(iter, I...)
376+
indices = map(iter.indices, I) do r, i
377+
@inbounds getindex(r, i)
378+
end
379+
CartesianIndices(indices)
376380
end
377381
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N},
378382
C::CartesianIndices{N}) where {N}
379-
CartesianIndices(getindex.(iter.indices, C.indices))
383+
getindex(iter, C.indices...)
380384
end
385+
@inline Base.getindex(iter::CartesianIndices{0}, ::CartesianIndices{0}) = iter
381386

382387
# If dimensions permit, we may index into a CartesianIndices directly instead of constructing a SubArray wrapper
383388
@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)