Skip to content

Commit 66a3cc9

Browse files
adienesKristofferC
authored andcommitted
Switch from segfault to zip behavior for mismatched indices in map! (#56673)
(cherry picked from commit 0947114)
1 parent bcb103a commit 66a3cc9

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

base/abstractarray.jl

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3412,12 +3412,19 @@ function ith_all(i, as)
34123412
end
34133413

34143414
function map_n!(f::F, dest::AbstractArray, As) where F
3415-
idxs1 = LinearIndices(As[1])
3416-
@boundscheck LinearIndices(dest) == idxs1 && all(x -> LinearIndices(x) == idxs1, As)
3417-
for i = idxs1
3418-
@inbounds I = ith_all(i, As)
3419-
val = f(I...)
3420-
@inbounds dest[i] = val
3415+
idxs = LinearIndices(dest)
3416+
if all(x -> LinearIndices(x) == idxs, As)
3417+
for i in idxs
3418+
@inbounds as = ith_all(i, As)
3419+
val = f(as...)
3420+
@inbounds dest[i] = val
3421+
end
3422+
else
3423+
for (i, Is...) in zip(eachindex(dest), map(eachindex, As)...)
3424+
as = ntuple(j->getindex(As[j], Is[j]), length(As))
3425+
val = f(as...)
3426+
dest[i] = val
3427+
end
34213428
end
34223429
return dest
34233430
end

test/abstractarray.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -910,6 +910,26 @@ include("generic_map_tests.jl")
910910
generic_map_tests(map, map!)
911911
@test map!(-, [1]) == [-1]
912912

913+
@testset "#30624" begin
914+
### unstructured
915+
@test map!(+, ones(3), ones(3), ones(3), [1]) == [3, 1, 1]
916+
@test map!(+, ones(3), [1], ones(3), ones(3)) == [3, 1, 1]
917+
@test map!(+, [1], [1], [], []) == [1]
918+
@test map!(+, [[1]], [1], [], []) == [[1]]
919+
920+
# TODO: decide if input axes & lengths should be validated
921+
# @test_throws BoundsError map!(+, ones(1), ones(2))
922+
# @test_throws BoundsError map!(+, ones(1), ones(2, 2))
923+
924+
@test map!(+, ones(3), view(ones(2, 3), 1:2, 2:3), ones(3)) == [2, 2, 2]
925+
@test map!(+, ones(3), ones(2, 2), ones(3)) == [2, 2, 2]
926+
927+
### structured (all mapped arguments are <:AbstractArray equal ndims > 1)
928+
@test map!(+, ones(4), ones(2, 2), ones(2, 2)) == [2, 2, 2, 2]
929+
@test map!(+, ones(4), ones(2, 2), ones(1, 2)) == [2, 2, 1, 1]
930+
# @test_throws BoundsError map!(+, ones(3), ones(2, 2), ones(2, 2))
931+
end
932+
913933
test_UInt_indexing(TestAbstractArray)
914934
test_13315(TestAbstractArray)
915935
test_checksquare()

0 commit comments

Comments
 (0)