-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
support ConstructionBase: constructorof and setproperties (#319)
- Loading branch information
Showing
3 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
using ConstructionBase | ||
|
||
# (named)tuple eltypes: components/fields are all that's needed for the StructArray() constructor | ||
ConstructionBase.constructorof(::Type{<:StructArray{<:Union{Tuple, NamedTuple}}}) = StructArray | ||
|
||
# other eltypes: need to pass eltype to the constructor in addition to components | ||
ConstructionBase.constructorof(::Type{<:StructArray{T}}) where {T} = function(comps::CT) where {CT} | ||
# the resulting eltype is like T, but potentially with different type parameters, eg Complex{Int} -> Complex{Float64} | ||
# probe its constructorof to get the right concrete type | ||
ET = Base.promote_op(constructorof(T), map(eltype, fieldtypes(CT))...) | ||
StructArray{ET}(comps) | ||
end | ||
|
||
# two methods with the same body, required to avoid ambiguities | ||
# just redirect setproperties to constructorof | ||
ConstructionBase.setproperties(x::StructArray, patch::NamedTuple) = constructorof(typeof(x))(setproperties(getproperties(x), patch)) | ||
ConstructionBase.setproperties(x::StructArray, patch::Tuple) = constructorof(typeof(x))(setproperties(getproperties(x), patch)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters