Skip to content

Commit 68399d6

Browse files
authored
Add interface support for LinearAlgebra.Diagonal (#16)
1 parent aceca8c commit 68399d6

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/wrappers.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,20 @@ for type in (:Adjoint, :PermutedDimsArray, :ReshapedArray, :SubArray, :Transpose
161161
end
162162
end
163163
end
164+
165+
using LinearAlgebra: Diagonal
166+
@interface ::AbstractArrayInterface storedvalues(D::Diagonal) = LinearAlgebra.diag(D)
167+
@interface ::AbstractArrayInterface eachstoredindex(D::Diagonal) =
168+
LinearAlgebra.diagind(D, IndexCartesian())
169+
@interface ::AbstractArrayInterface isstored(D::Diagonal, i::Int, j::Int) =
170+
i == j && Base.checkbounds(Bool, D, i, j)
171+
@interface ::AbstractArrayInterface function getstoredindex(D::Diagonal, i::Int, j::Int)
172+
return D.diag[i]
173+
end
174+
@interface ::AbstractArrayInterface function getunstoredindex(D::Diagonal, i::Int, j::Int)
175+
return zero(eltype(D))
176+
end
177+
@interface ::AbstractArrayInterface function setstoredindex!(D::Diagonal, v, i::Int, j::Int)
178+
D.diag[i] = v
179+
return D
180+
end

test/basics/test_diagonal.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using LinearAlgebra: Diagonal, diagind
2+
using SparseArraysBase:
3+
eachstoredindex,
4+
getstoredindex,
5+
getunstoredindex,
6+
setstoredindex!,
7+
isstored,
8+
storedlength,
9+
storedpairs,
10+
storedvalues
11+
12+
using Test: @test, @testset
13+
14+
elts = (Float32, Float64, Complex{Float32}, Complex{Float64})
15+
16+
@testset "Diagonal{$T}" for T in elts
17+
L = 4
18+
D = Diagonal(rand(T, 4))
19+
@test storedlength(D) == 4
20+
@test eachstoredindex(D) == diagind(D, IndexCartesian())
21+
@test isstored(D, 2, 2)
22+
@test getstoredindex(D, 2, 2) == D[2, 2]
23+
@test !isstored(D, 2, 1)
24+
@test getunstoredindex(D, 2, 2) == zero(T)
25+
end

0 commit comments

Comments
 (0)