Skip to content

Commit 3ea7f6c

Browse files
mcabbottsimonbyrne
authored andcommitted
add bounds check to Slices indexing (#47622)
Co-authored-by: Simon Byrne <[email protected]> (cherry picked from commit d7363d8)
1 parent f17d1df commit 3ea7f6c

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

base/slicearray.jl

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ the ordering of the dimensions will match those in `dims`. If `drop = false`, th
8585
`Slices` will have the same dimensionality as the underlying array, with inner
8686
dimensions having size 1.
8787
88-
See [`stack`](@ref)`(slices; dims)` for the inverse of `eachcol(A; dims::Integer, drop=true)`.
88+
See [`stack`](@ref)`(slices; dims)` for the inverse of `eachslice(A; dims::Integer)`.
8989
9090
See also [`eachrow`](@ref), [`eachcol`](@ref), [`mapslices`](@ref) and [`selectdim`](@ref).
9191
@@ -232,9 +232,13 @@ size(s::Slices) = map(length, s.axes)
232232
return map(l -> l === (:) ? (:) : c[l], s.slicemap)
233233
end
234234

235-
Base.@propagate_inbounds getindex(s::Slices{P,SM,AX,S,N}, I::Vararg{Int,N}) where {P,SM,AX,S,N} =
236-
view(s.parent, _slice_index(s, I...)...)
237-
Base.@propagate_inbounds setindex!(s::Slices{P,SM,AX,S,N}, val, I::Vararg{Int,N}) where {P,SM,AX,S,N} =
238-
s.parent[_slice_index(s, I...)...] = val
235+
@inline function getindex(s::Slices{P,SM,AX,S,N}, I::Vararg{Int,N}) where {P,SM,AX,S,N}
236+
@boundscheck checkbounds(s, I...)
237+
@inbounds view(s.parent, _slice_index(s, I...)...)
238+
end
239+
@inline function setindex!(s::Slices{P,SM,AX,S,N}, val, I::Vararg{Int,N}) where {P,SM,AX,S,N}
240+
@boundscheck checkbounds(s, I...)
241+
@inbounds s.parent[_slice_index(s, I...)...] = val
242+
end
239243

240244
parent(s::Slices) = s.parent

test/arrayops.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2293,6 +2293,15 @@ end
22932293
f2(a) = eachslice(a, dims=2)
22942294
@test (@inferred f2(a)) == eachcol(a)
22952295
end
2296+
2297+
@testset "eachslice bounds checking" begin
2298+
# https://github.com/JuliaLang/julia/pull/32310#issuecomment-1146911510
2299+
A = eachslice(rand(2,3), dims = 2, drop = false)
2300+
@test_throws BoundsError A[2, 1]
2301+
@test_throws BoundsError A[4]
2302+
@test_throws BoundsError A[2,3] = [4,5]
2303+
@test_throws BoundsError A[2,3] .= [4,5]
2304+
end
22962305
end
22972306

22982307
###

0 commit comments

Comments
 (0)