Convert or copy to StaticArrays.MArray


#1

I’m using StaticArrays, and I have a function like the following

function (obj::SomeObject{D}, x::AbstractVector{Int}) where {D}
    x_mutable = MVector{D,Int}(x)
    # [... mutate `x_mutable` in some way, based on obj]
    return SVector(x_mutable)
end

Essentially, I need to copy x to an MVector, modify it, and then return an SVector. But if I happen to pass an MVector to this function, x_mutable is equivalent to x (i.e. x === x_mutable). But I really want a copy instead.

Is there a simple way to “convert” to an MVector, but to perform a copy if the object was already an MVector?

The obvious solution of copy(MVector(x)) results in an unnecessary copy when x is not an MVector.

Thanks in advance!

EDIT: I realize that by using multiple dispatch I could easily create a convert_or_copy function myself. My real question is whether such a pattern already exists in StaticArrays or elsewhere.


#2

https://github.com/JuliaLang/julia/issues/23107

Conclusion MVector should always copy.


#3

Aha, it sounds like a bug should be filed against StaticArrays, then:

julia> using StaticArrays

julia> a = @MVector [1,2,3]
3-element MVector{3,Int64}:
 1
 2
 3

julia> MVector(a) === a
true

Thanks for the help.


#4

As a work around, for now you you could define a second method that takes x::MVector and copies x.


#5

Issue filed: https://github.com/JuliaArrays/StaticArrays.jl/issues/335