Skip to content

Commit

Permalink
Prevent mapslices from mutating the original array
Browse files Browse the repository at this point in the history
  • Loading branch information
timholy committed Jul 4, 2016
1 parent 3e1878b commit 35d7564
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 4 additions & 2 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1417,7 +1417,8 @@ function mapslices(f, A::AbstractArray, dims::AbstractVector)
idx[d] = Colon()
end

r1 = f(view(A, idx...))
Aslice = A[idx...]
r1 = f(Aslice)

# determine result size and allocate
Rsize = copy(dimsA)
Expand Down Expand Up @@ -1449,7 +1450,8 @@ function mapslices(f, A::AbstractArray, dims::AbstractVector)
for i in 1:nidx
idx[otherdims[i]] = ridx[otherdims[i]] = I.I[i]
end
R[ridx...] = f(view(A, idx...))
_unsafe_getindex!(Aslice, A, idx...)
R[ridx...] = f(Aslice)
end
end

Expand Down
6 changes: 6 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,12 @@ let
n3a = mapslices(x-> ones(1,6), c, [2,3])
@test size(n1a) == (1,6,4) && size(n2a) == (1,3,6) && size(n3a) == (2,1,6)
@test size(n1) == (6,1,4) && size(n2) == (6,3,1) && size(n3) == (2,6,1)

# mutating functions
o = ones(3, 4)
m = mapslices(x->fill!(x, 0), o, 2)
@test m == zeros(3, 4)
@test o == ones(3, 4)
end


Expand Down

0 comments on commit 35d7564

Please sign in to comment.