Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support named properties in StructArray{SVector} #277

Merged
merged 1 commit into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions ext/StructArraysStaticArraysExt.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module StructArraysStaticArraysExt

using StructArrays
using StaticArrays: StaticArray, FieldArray, tuple_prod
using StaticArrays: StaticArray, FieldArray, tuple_prod, SVector, MVector

"""
StructArrays.staticschema(::Type{<:StaticArray{S, T}}) where {S, T}
Expand All @@ -22,7 +22,16 @@ which subtypes `FieldArray`.
end
end
StructArrays.createinstance(::Type{T}, args...) where {T<:StaticArray} = T(args)
StructArrays.component(s::StaticArray, i) = getindex(s, i)
StructArrays.component(s::StaticArray, i::Integer) = getindex(s, i)

function StructArrays.component(s::StructArray{<:Union{SVector,MVector}}, key::Symbol)
i = key == :x ? 1 :
key == :y ? 2 :
key == :z ? 3 :
key == :w ? 4 :
throw(ArgumentError("invalid key $key"))
StructArrays.component(s, i)
end

# invoke general fallbacks for a `FieldArray` type.
@inline function StructArrays.staticschema(T::Type{<:FieldArray})
Expand Down
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1405,6 +1405,12 @@ end
@test StructArrays.components(x) == ([1.0,2.0], [2.0,3.0])
@test x .+ y == StructArray([StaticVectorType{2}(Float64[2*i+1;2*i+3]) for i = 1:2])
end
for StaticVectorType = [SVector, MVector]
x = @inferred StructArray([StaticVectorType{2}(Float64[i;i+1]) for i = 1:2])
# numbered and named property access:
@test x.:1 == [1.0,2.0]
@test x.y == [2.0,3.0]
end
# test broadcast + components for general arrays
for StaticArrayType = [SArray, MArray, SizedArray]
x = @inferred StructArray([StaticArrayType{Tuple{1,2}}(ones(1,2) .+ i) for i = 0:1])
Expand Down
Loading