From 2fae1a102e934b13a3ff0a43f77dbd5b548e4244 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=83=8E=E3=83=AB?= Date: Tue, 5 Sep 2023 02:57:32 -0400 Subject: [PATCH] Correctly set zeros with `fill!(::SubArray)` and fix its return value (#433) --- src/sparsematrix.jl | 5 +++-- test/sparsematrix_constructors_indexing.jl | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/sparsematrix.jl b/src/sparsematrix.jl index 1703c870..165a7046 100644 --- a/src/sparsematrix.jl +++ b/src/sparsematrix.jl @@ -3179,7 +3179,8 @@ function Base.fill!(V::SubArray{Tv, <:Any, <:AbstractSparseMatrixCSC{Tv}, <:Tupl else _spsetnz_setindex!(A, convert(Tv, x), I, J) end - return _checkbuffers(A) + _checkbuffers(A) + V end """ Helper method for immediately preceding fill! method. For all (i,j) such that i in I and @@ -3207,7 +3208,7 @@ function _spsetz_setindex!(A::AbstractSparseMatrixCSC, kI > lengthI && break entrykIrow = I[kI] else # entrykArow == entrykIrow - nonzeros(A)[kA] = 0 + nonzeros(A)[kA] = zero(eltype(A)) kA += 1 kI += 1 (kA > coljAlastk || kI > lengthI) && break diff --git a/test/sparsematrix_constructors_indexing.jl b/test/sparsematrix_constructors_indexing.jl index 5aad5628..0278c4be 100644 --- a/test/sparsematrix_constructors_indexing.jl +++ b/test/sparsematrix_constructors_indexing.jl @@ -342,7 +342,7 @@ end A = rand(5,5) A´ = similar(A) Ac = copyto!(A, B) - @test Ac === A + @test Ac === A @test A == copyto!(A´, Matrix(B)) # Test copyto!(dense, Rdest, sparse, Rsrc) A = rand(5,5) @@ -1363,7 +1363,9 @@ end a = sprand(10, 10, 0.2) b = copy(a) sa = view(a, 1:10, 2:3) - fill!(sa, 0.0) + sa_filled = fill!(sa, 0.0) + # `fill!` should return the sub array instead of its parent. + @test sa_filled === sa b[1:10, 2:3] .= 0.0 @test a == b A = sparse([1], [1], [Vector{Float64}(undef, 3)], 3, 3) @@ -1375,6 +1377,17 @@ end B[1, jj] = [4.0, 5.0, 6.0] end @test A == B + + # https://github.com/JuliaSparse/SparseArrays.jl/pull/433 + struct Foo + x::Int + end + Base.zero(::Type{Foo}) = Foo(0) + Base.zero(::Foo) = zero(Foo) + C = sparse([1], [1], [Foo(3)], 3, 3) + sC = view(C, 1:1, 1:2) + fill!(sC, zero(Foo)) + @test C[1:1, 1:2] == zeros(Foo, 1, 2) end using Base: swaprows!, swapcols!