Skip to content

Commit

Permalink
provide type-inferred length
Browse files Browse the repository at this point in the history
resolves jonniedie#138
Need to check correct general computation of length of Axis.
  • Loading branch information
bgctw committed Jun 3, 2022
1 parent efd8cc6 commit 0b9a40e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/axis.jl
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ Base.merge(axs::Axis...) = Axis(merge(indexmap.(axs)...))

Base.firstindex(ax::AbstractAxis) = first(viewindex(first(indexmap(ax))))
Base.lastindex(ax::AbstractAxis) = last(viewindex(last(indexmap(ax))))
Base.length(ax::AbstractAxis) = lastindex(ax) - firstindex(ax) + 1

Base.keys(ax::AbstractAxis) = keys(indexmap(ax))

Expand Down
4 changes: 4 additions & 0 deletions src/componentarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ last_index(x) = last(x)
last_index(x::ViewAxis) = last_index(viewindex(x))
last_index(x::AbstractAxis) = last_index(last(indexmap(x)))

# length information is in Axis, use it to make SVector creation type stable
Base.length(ca::ComponentArray) = prod(length.(getaxes(ca)))
Base.size(ca::ComponentArray) = map(length, getaxes(ca))

# Reduce singleton dimensions
remove_nulls() = ()
remove_nulls(x1, args...) = (x1, remove_nulls(args...)...)
Expand Down
9 changes: 9 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,15 @@ end
@test convert(Cholesky{Float32,Matrix{Float32}}, chol).factors isa Matrix{Float32}
end

@testset "length typestable" begin
# function boundary, so that cv is type-inferred
test_create_svector = (cv) -> SVector{length(cv)}(cv)
@inferred test_create_svector(ComponentVector(a=1:3));
@inferred test_create_svector(cmat);
test_create_smatrix = (cmat) -> SMatrix{size(cmat)...}(cmat)
@test (@inferred test_create_smatrix(cmat)) isa SMatrix
end;

@testset "Autodiff" begin
include("autodiff_tests.jl")
end

0 comments on commit 0b9a40e

Please sign in to comment.