Skip to content

Commit d9fafab

Browse files
authored
Specialize one for the SizedArray test helper (#58209)
Since the size of the array is encoded in the type, we may define `one` on the type. This is useful in certain linear algebra contexts.
1 parent d992554 commit d9fafab

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

test/abstractarray.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2191,6 +2191,22 @@ end
21912191

21922192
@test one(Mat([1 2; 3 4])) == Mat([1 0; 0 1])
21932193
@test one(Mat([1 2; 3 4])) isa Mat
2194+
2195+
@testset "SizedArray" begin
2196+
S = [1 2; 3 4]
2197+
A = SizedArrays.SizedArray{(2,2)}(S)
2198+
@test one(A) == one(typeof(A))
2199+
@test oneunit(A) == oneunit(typeof(A))
2200+
M = fill(A, 2, 2)
2201+
O = one(M)
2202+
for I in CartesianIndices(M)
2203+
if I[1] == I[2]
2204+
@test O[I] == one(S)
2205+
else
2206+
@test O[I] == zero(S)
2207+
end
2208+
end
2209+
end
21942210
end
21952211

21962212
@testset "copyto! with non-AbstractArray src" begin

test/testhelpers/SizedArrays.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ Base.axes(a::SizedArray) = map(SOneTo, size(a))
5454
Base.getindex(A::SizedArray, i...) = getindex(A.data, i...)
5555
Base.setindex!(A::SizedArray, v, i...) = setindex!(A.data, v, i...)
5656
Base.zero(::Type{T}) where T <: SizedArray = SizedArray{size(T)}(zeros(eltype(T), size(T)))
57+
function Base.one(::Type{SizedMatrix{SZ,T,A}}) where {SZ,T,A}
58+
allequal(SZ) || throw(DimensionMismatch("multiplicative identity defined only for square matrices"))
59+
D = diagm(fill(one(T), SZ[1]))
60+
SizedArray{SZ}(convert(A, D))
61+
end
5762
Base.parent(S::SizedArray) = S.data
5863
+(S1::SizedArray{SZ}, S2::SizedArray{SZ}) where {SZ} = SizedArray{SZ}(S1.data + S2.data)
5964
==(S1::SizedArray{SZ}, S2::SizedArray{SZ}) where {SZ} = S1.data == S2.data

0 commit comments

Comments
 (0)