Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
blegat committed Jul 3, 2024
1 parent d21d562 commit 0ae59a4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/sparse_coeffs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,17 @@ function Base.copy(sc::SparseCoefficients)
return SparseCoefficients(copy(keys(sc)), copy(values(sc)))
end

function _search(keys::Tuple, key)
# `searchsortedfirst` is not defined for `Tuple`
return findfirst(isequal(key), keys)
end

function _search(keys, key::K) where {K}
return searchsortedfirst(keys, key; lt = comparable(K))
end

function Base.getindex(sc::SparseCoefficients{K}, key::K) where {K}
k = searchsortedfirst(sc.basis_elements, key; lt = comparable(K))
k = _search(sc.basis_elements, key)
if k in eachindex(sc.basis_elements)
v = sc.values[k]
if sc.basis_elements[k] == key
Expand All @@ -30,7 +39,7 @@ end
function Base.setindex!(sc::SparseCoefficients{K}, val, key::K) where {K}
k = searchsortedfirst(sc.basis_elements, key; lt = comparable(K))
if k in eachindex(sc.basis_elements) && sc.basis_elements[k] == key
sc.values[k] += val
sc.values[k] = val
else
insert!(sc.basis_elements, k, key)
insert!(sc.values, k, val)
Expand Down
8 changes: 8 additions & 0 deletions test/caching_allocations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,12 @@ end
@test _test_op(+, Z, Y) == _test_op(+, Y, Y)
@test _test_op(-, Z, Z) == _test_op(*, 0, Z)
@test _test_op(-, Z, Z) == _test_op(-, Y, Z)

for X in [Y, Z]
c = coeffs(X)
res = 2 .* c
@test c .* 2 == res
@test c .+ 1 == res
@test 1 .+ c == res
end
end

0 comments on commit 0ae59a4

Please sign in to comment.