Skip to content

Add bounds check to Slices indexing #47622

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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