Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/setindex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ Base.@propagate_inbounds function setindex(args...)
end

Base.@propagate_inbounds function setindex(xs::AbstractArray, v, I...)
T = promote_type(eltype(xs), typeof(v))
# we need to distinguish between scalar and sliced assignment
I_normalized = Base.to_indices(xs, I)
T = promote_type(eltype(xs), I_normalized isa Tuple{Vararg{Integer}} ? typeof(v) : eltype(v))
ys = similar(xs, T)
if eltype(xs) !== Union{}
copy!(ys, xs)
end
ys[I...] = v
ys[I_normalized...] = v
return ys
end

Expand Down
3 changes: 3 additions & 0 deletions test/test_setindex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ end
@test @set(arr[1] = 10) == [10, 2, 3]
@test arr == [1,2,3]
@test Setfield.setindex(arr, 10.0, 1) ==ₜ Float64[10.0, 2.0, 3.0]
@test Setfield.setindex(ones(2, 2), zeros(2), 1, :) ==ₜ Float64[0.0 0.0; 1.0 1.0]
@test Setfield.setindex(ones(BigInt, 2, 2), zeros(Float32, 2), 1, :) ==ₜ BigFloat[0.0 0.0; 1.0 1.0]
@test Setfield.setindex(fill(ones(1), 2, 2), [im, im], :, 1) ==ₜ hcat([im, im], [[1.0], [1.0]])

d = Dict(:a => 1, :b => 2)
@test_throws MethodError Base.setindex(d, 10, :a)
Expand Down