Skip to content

Commit 7c923f9

Browse files
adienesLebedevRI
authored andcommitted
Switch from segfault to zip behavior for mismatched indices in map! (JuliaLang#56673)
1 parent 788bf13 commit 7c923f9

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
@@ -3417,12 +3417,19 @@ function ith_all(i, as)
34173417
end
34183418

34193419
function map_n!(f::F, dest::AbstractArray, As) where F
3420-
idxs1 = LinearIndices(As[1])
3421-
@boundscheck LinearIndices(dest) == idxs1 && all(x -> LinearIndices(x) == idxs1, As)
3422-
for i = idxs1
3423-
@inbounds I = ith_all(i, As)
3424-
val = f(I...)
3425-
@inbounds dest[i] = val
3420+
idxs = LinearIndices(dest)
3421+
if all(x -> LinearIndices(x) == idxs, As)
3422+
for i in idxs
3423+
@inbounds as = ith_all(i, As)
3424+
val = f(as...)
3425+
@inbounds dest[i] = val
3426+
end
3427+
else
3428+
for (i, Is...) in zip(eachindex(dest), map(eachindex, As)...)
3429+
as = ntuple(j->getindex(As[j], Is[j]), length(As))
3430+
val = f(as...)
3431+
dest[i] = val
3432+
end
34263433
end
34273434
return dest
34283435
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)