Skip to content
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

Check bounds upon construction of SubArrays. #10296

Merged
merged 2 commits into from Feb 24, 2015
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 14 additions & 4 deletions base/subarray.jl
Expand Up @@ -35,7 +35,12 @@ parentindexes(a::AbstractArray) = ntuple(ndims(a), i->1:size(a,i))
# Drops singleton dimensions (those indexed with a scalar)
slice(A::AbstractArray, I::ViewIndex...) = _slice(A, I)
slice(A::AbstractArray, I::(ViewIndex...)) = _slice(A, I)
stagedfunction _slice{T,NP,IndTypes}(A::AbstractArray{T,NP}, I::IndTypes)
function _slice(A, I)
checkbounds(A, I...)
slice_unsafe(A, I)
end

stagedfunction slice_unsafe{T,NP,IndTypes}(A::AbstractArray{T,NP}, I::IndTypes)
N = 0
sizeexprs = Array(Any, 0)
for k = 1:length(I)
Expand All @@ -59,7 +64,12 @@ end
# other singletons)
sub(A::AbstractArray, I::ViewIndex...) = _sub(A, I)
sub(A::AbstractArray, I::(ViewIndex...)) = _sub(A, I)
stagedfunction _sub{T,NP,IndTypes}(A::AbstractArray{T,NP}, I::IndTypes)
function _sub(A, I)
checkbounds(A, I...)
sub_unsafe(A, I)
end

stagedfunction sub_unsafe{T,NP,IndTypes}(A::AbstractArray{T,NP}, I::IndTypes)
sizeexprs = Array(Any, 0)
Itypes = Array(Any, 0)
Iexprs = Array(Any, 0)
Expand Down Expand Up @@ -93,7 +103,7 @@ end

# Constructing from another SubArray
# This "pops" the old SubArray and creates a more compact one
stagedfunction _slice{T,NV,PV,IV,PLD,IndTypes}(V::SubArray{T,NV,PV,IV,PLD}, I::IndTypes)
stagedfunction slice_unsafe{T,NV,PV,IV,PLD,IndTypes}(V::SubArray{T,NV,PV,IV,PLD}, I::IndTypes)
N = 0
sizeexprs = Array(Any, 0)
indexexprs = Array(Any, 0)
Expand Down Expand Up @@ -163,7 +173,7 @@ stagedfunction _slice{T,NV,PV,IV,PLD,IndTypes}(V::SubArray{T,NV,PV,IV,PLD}, I::I
end
end

stagedfunction _sub{T,NV,PV,IV,PLD,IndTypes}(V::SubArray{T,NV,PV,IV,PLD}, I::IndTypes)
stagedfunction sub_unsafe{T,NV,PV,IV,PLD,IndTypes}(V::SubArray{T,NV,PV,IV,PLD}, I::IndTypes)
N = length(I)
while N > 0 && I[N] <: Real
N -= 1
Expand Down
10 changes: 10 additions & 0 deletions test/subarray.jl
Expand Up @@ -374,3 +374,13 @@ msk[2,1] = false
sA = sub(A, :, :, 1)
sA[msk] = 1.0
@test sA[msk] == ones(countnz(msk))

# bounds checking upon construction; see #4044, #10296
@test_throws BoundsError sub(1:10, 8:11)
A = reshape(1:20, 5, 4)
sA = sub(A, 1:2, 1:3)
@test_throws BoundsError sub(sA, 1:3, 1:3)
@test_throws BoundsError sub(sA, 1:2, 1:4)
sub(sA, 1:2, 1:2)
@test_throws BoundsError sub(A, 17:23)
sub(A, 17:20)