You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
90: Add type assert to SparseContainers for inference r=charleskawczynski a=charleskawczynski
This PR adds a type assertion to SparseContainers, which seems to improve inference.
##### main:
```julia
struct SparseContainer{T,SIM}
data::T
function SparseContainer(compressed_data::T, sparse_index_map::Tuple) where {T}
return new{T, sparse_index_map}(compressed_data)
end
end
Base.parent(sc::SparseContainer) = sc.data
`@inline` Base.getindex(sc::SparseContainer, i::Int) = _getindex_sparse(sc, Val(i))
`@generated` function _getindex_sparse(sc::SparseContainer{T,SIM}, ::Val{i}) where {T, SIM, i}
j = findfirst(k -> k == i, SIM)
j == nothing && error("No index $i found in sparse index map $(SIM)")
return :(sc.data[$j])
end
a1 = ones(3) .* 1
a2 = ones(3) .* 2
a3 = ones(3) .* 3
a4 = ones(3) .* 4
v = SparseContainer((a1,a2,a3,a4), (1,3,5,7))
`@code_typed` v[1]
```
##### This PR:
```julia
struct SparseContainer{ET, SIM, T}
data::T
function SparseContainer(compressed_data::T, sparse_index_map::Tuple) where {T}
`@assert` all(map(x-> eltype(compressed_data) .== typeof(x), compressed_data))
return new{eltype(compressed_data), sparse_index_map, T}(compressed_data)
end
end
Base.parent(sc::SparseContainer) = sc.data
`@inline` function Base.getindex(sc::SparseContainer{ET}, i::Int) where {ET}
return _getindex_sparse(sc, Val(i))::ET
end
`@generated` function _getindex_sparse(sc::SparseContainer{ET,SIM}, ::Val{i})::ET where {ET, SIM, i}
j = findfirst(k -> k == i, SIM)
j == nothing && error("No index $i found in sparse index map $(SIM)")
return :(sc.data[$j])
end
a1 = ones(3) .* 1
a2 = ones(3) .* 2
a3 = ones(3) .* 3
a4 = ones(3) .* 4
v = SparseContainer((a1,a2,a3,a4), (1,3,5,7))
`@code_typed` v[1]
```
Co-authored-by: Charles Kawczynski <[email protected]>
0 commit comments