Skip to content

Commit

Permalink
add bounds check to Slices indexing (#47622)
Browse files Browse the repository at this point in the history
Co-authored-by: Simon Byrne <simonbyrne@gmail.com>
  • Loading branch information
mcabbott and simonbyrne authored Dec 20, 2022
1 parent 1f0700a commit d7363d8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
14 changes: 9 additions & 5 deletions base/slicearray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ the ordering of the dimensions will match those in `dims`. If `drop = false`, th
`Slices` will have the same dimensionality as the underlying array, with inner
dimensions having size 1.
See [`stack`](@ref)`(slices; dims)` for the inverse of `eachcol(A; dims::Integer, drop=true)`.
See [`stack`](@ref)`(slices; dims)` for the inverse of `eachslice(A; dims::Integer)`.
See also [`eachrow`](@ref), [`eachcol`](@ref), [`mapslices`](@ref) and [`selectdim`](@ref).
Expand Down Expand Up @@ -232,9 +232,13 @@ size(s::Slices) = map(length, s.axes)
return map(l -> l === (:) ? (:) : c[l], s.slicemap)
end

Base.@propagate_inbounds getindex(s::Slices{P,SM,AX,S,N}, I::Vararg{Int,N}) where {P,SM,AX,S,N} =
view(s.parent, _slice_index(s, I...)...)
Base.@propagate_inbounds setindex!(s::Slices{P,SM,AX,S,N}, val, I::Vararg{Int,N}) where {P,SM,AX,S,N} =
s.parent[_slice_index(s, I...)...] = val
@inline function getindex(s::Slices{P,SM,AX,S,N}, I::Vararg{Int,N}) where {P,SM,AX,S,N}
@boundscheck checkbounds(s, I...)
@inbounds view(s.parent, _slice_index(s, I...)...)
end
@inline function setindex!(s::Slices{P,SM,AX,S,N}, val, I::Vararg{Int,N}) where {P,SM,AX,S,N}
@boundscheck checkbounds(s, I...)
@inbounds s.parent[_slice_index(s, I...)...] = val
end

parent(s::Slices) = s.parent
9 changes: 9 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2293,6 +2293,15 @@ end
f2(a) = eachslice(a, dims=2)
@test (@inferred f2(a)) == eachcol(a)
end

@testset "eachslice bounds checking" begin
# https://github.com/JuliaLang/julia/pull/32310#issuecomment-1146911510
A = eachslice(rand(2,3), dims = 2, drop = false)
@test_throws BoundsError A[2, 1]
@test_throws BoundsError A[4]
@test_throws BoundsError A[2,3] = [4,5]
@test_throws BoundsError A[2,3] .= [4,5]
end
end

###
Expand Down

0 comments on commit d7363d8

Please sign in to comment.