From 160139e0c941e3e6af5bcb189a87c225edd3e2de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Legat?= Date: Fri, 18 Sep 2026 09:42:43 +0200 Subject: [PATCH] Implement mutable_copy for SparseVector --- src/implementations/SparseArrays.jl | 7 +++++++ test/test_sparse_arrays.jl | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/implementations/SparseArrays.jl b/src/implementations/SparseArrays.jl index 9ce1a61..6c50d33 100644 --- a/src/implementations/SparseArrays.jl +++ b/src/implementations/SparseArrays.jl @@ -9,6 +9,13 @@ const _SparseMat = SparseArrays.SparseMatrixCSC +function mutable_copy(v::SparseArrays.SparseVector) + result = copy(v) + vals = SparseArrays.nonzeros(result) + map!(copy_if_mutable, vals, vals) + return result +end + function undef_array( ::Type{_SparseMat{Tv,Ti}}, rows::Base.OneTo, diff --git a/test/test_sparse_arrays.jl b/test/test_sparse_arrays.jl index c294cab..3de81cc 100644 --- a/test/test_sparse_arrays.jl +++ b/test/test_sparse_arrays.jl @@ -21,6 +21,32 @@ function runtests() return end +function test_mutable_copy_sparse_vector() + for T in (Int, BigInt) + v = SparseArrays.SparseVector(1_000_000, Int32[2, 7, 13], T[1, 0, 3]) + w = MA.mutable_copy(v) + @test typeof(w) === typeof(v) + @test length(w) == length(v) + @test SparseArrays.nonzeroinds(w) == Int32[2, 7, 13] + @test SparseArrays.nonzeros(w) == T[1, 0, 3] + @test SparseArrays.nonzeroinds(w) !== SparseArrays.nonzeroinds(v) + @test SparseArrays.nonzeros(w) !== SparseArrays.nonzeros(v) + if T === BigInt + MA.operate!(+, SparseArrays.nonzeros(w)[1], 1) + @test w[2] == 2 + @test v[2] == 1 + end + w[7] = 4 + @test v[7] == 0 + end + v = SparseArrays.SparseVector(10, Int32[], BigInt[]) + w = MA.mutable_copy(v) + @test typeof(w) === typeof(v) + @test length(w) == 10 + @test SparseArrays.nnz(w) == 0 + return +end + function test_spmatmul() Random.seed!(1234) for m in [1, 2, 3, 5, 11]