Skip to content

Commit 1b512c9

Browse files
johnnychen94LilithHafner
authored andcommitted
Eagerly do boundscheck when indexing CartesianIndices with CartesianIndices (JuliaLang#42235)
1 parent a634722 commit 1b512c9

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
@@ -355,14 +355,19 @@ module IteratorsMD
355355
# CartesianIndices act as a multidimensional range, so cartesian indexing of CartesianIndices
356356
# with compatible dimensions may be seen as indexing into the component ranges.
357357
# This may use the special indexing behavior implemented for ranges to return another CartesianIndices
358-
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N,R},
358+
@inline function Base.getindex(iter::CartesianIndices{N,R},
359359
I::Vararg{Union{OrdinalRange{<:Integer, <:Integer}, Colon}, N}) where {N,R}
360-
CartesianIndices(getindex.(iter.indices, I))
360+
@boundscheck checkbounds(iter, I...)
361+
indices = map(iter.indices, I) do r, i
362+
@inbounds getindex(r, i)
363+
end
364+
CartesianIndices(indices)
361365
end
362366
@propagate_inbounds function Base.getindex(iter::CartesianIndices{N},
363367
C::CartesianIndices{N}) where {N}
364-
CartesianIndices(getindex.(iter.indices, C.indices))
368+
getindex(iter, C.indices...)
365369
end
370+
@inline Base.getindex(iter::CartesianIndices{0}, ::CartesianIndices{0}) = iter
366371

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

0 commit comments

Comments
 (0)