Skip to content

Commit 8034cbc

Browse files
Merge pull request #420 from jlchan/jc/fix_similar_VoA
fix `Base.similar` for `VectorOfArray` of `AbstractArray{<:StaticArray}`
2 parents 19c7ba6 + 2ee1724 commit 8034cbc

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/vector_of_array.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,12 @@ function Base.similar(vec::VectorOfArray{
704704
return VectorOfArray(similar.(Base.parent(vec)))
705705
end
706706

707+
function Base.similar(vec::VectorOfArray{
708+
T, N, AT}) where {T, N, AT <: AbstractArray{<:StaticArraysCore.StaticVecOrMat{T}}}
709+
# this avoids behavior such as similar(SVector) returning an MVector
710+
return VectorOfArray(similar(Base.parent(vec)))
711+
end
712+
707713
@inline function Base.similar(VA::VectorOfArray, ::Type{T} = eltype(VA)) where {T}
708714
VectorOfArray(similar.(VA.u, T))
709715
end

test/copy_static_array_test.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,4 +120,14 @@ x = StructArray{SVector{2, Float64}}((randn(2), randn(2)))
120120
vx = VectorOfArray(x)
121121
vx2 = copy(vx) .+ 1
122122
ans = vx .+ vx2
123-
@test ans.u isa StructArray
123+
@test ans.u isa StructArray
124+
125+
# check that Base.similar(VectorOfArray{<:StaticArray}) returns the
126+
# same type as the original VectorOfArray
127+
x_staticvector = [SVector(0.0, 0.0) for _ in 1:2]
128+
x_structarray = StructArray{SVector{2, Float64}}((randn(2), randn(2)))
129+
x_mutablefv = [MutableFV(1.0, 2.0)]
130+
x_immutablefv = [ImmutableFV(1.0, 2.0)]
131+
for vec in [x_staticvector, x_structarray, x_mutablefv, x_immutablefv]
132+
@test typeof(similar(VectorOfArray(vec))) === typeof(VectorOfArray(vec))
133+
end

0 commit comments

Comments
 (0)