Skip to content

Commit fdb313a

Browse files
committed
Fix #4044
1 parent 7f7dca8 commit fdb313a

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

base/subarray.jl

+6-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ type SubArray{T,N,A<:AbstractArray,I<:(RangeIndex...,)} <: AbstractArray{T,N}
99
strides::Array{Int,1} # for accessing parent with linear indexes
1010
first_index::Int
1111

12+
# Note: no bounds-checking on construction. See issue #4044
1213
#linear indexing constructor (scalar)
1314
if N == 0 && length(I) == 1 && A <: Array
1415
function SubArray(p::A, i::(Int,))
@@ -71,7 +72,9 @@ function sub(A::SubArray, i::RangeIndex...)
7172
if isa(A.indexes[k], Int)
7273
newindexes[k] = A.indexes[k]
7374
else
74-
newindexes[k] = A.indexes[k][(isa(i[j],Int) && j<=L) ? (i[j]:i[j]) : i[j]]
75+
r = A.indexes[k]
76+
ri = (isa(i[j],Int) && j<=L) ? (i[j]:i[j]) : i[j]
77+
newindexes[k] = first(r) + (ri-1)*step(r)
7578
j += 1
7679
end
7780
end
@@ -95,7 +98,8 @@ function slice(A::SubArray, i::RangeIndex...)
9598
if isa(A.indexes[k], Int)
9699
newindexes[k] = A.indexes[k]
97100
else
98-
newindexes[k] = A.indexes[k][i[j]]
101+
r = A.indexes[k]
102+
newindexes[k] = first(r) + (i[j]-1)*step(r)
99103
j += 1
100104
end
101105
end

test/arrayops.jl

+17
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,23 @@ a = [5:8]
148148
@test parent(a) == a
149149
@test parentindexes(a) == (1:4,)
150150

151+
# Out-of-bounds construction. See #4044
152+
A = rand(7,7)
153+
rng = 1:4
154+
sA = sub(A, 2, rng-1)
155+
@test_throws sA[1,1]
156+
@test sA[1,2] == A[2,1]
157+
sA = sub(A, 2, rng)
158+
B = sub(sA, 1, rng-1)
159+
C = sub(B, 1, rng+1)
160+
@test C == sA
161+
sA = slice(A, 2, rng-1)
162+
@test_throws sA[1]
163+
@test sA[2] == A[2,1]
164+
sA = slice(A, 2, rng)
165+
B = slice(sA, rng-1)
166+
C = sub(B, rng+1)
167+
@test C == sA
151168

152169
# get
153170
let

0 commit comments

Comments
 (0)