Skip to content

Commit

Permalink
Merge pull request #17 from tkf/NamedTupleConstructor
Browse files Browse the repository at this point in the history
Type-stable constructorof(::Type{<:NamedTuple})(args...)
  • Loading branch information
tkf authored Oct 2, 2019
2 parents 702347f + 188b4ca commit bf245e2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/ConstructionBase.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ T{Int64,Int64}(10, 2)
getfield(parentmodule(T), nameof(T))
end

constructorof(::Type{<:Tuple}) = tuple
constructorof(::Type{<:NamedTuple{names}}) where names =
NamedTupleConstructor{names}()

struct NamedTupleConstructor{names} end

@generated function (::NamedTupleConstructor{names})(args...) where names
quote
Base.@_inline_meta
$(NamedTuple{names, Tuple{args...}})(args)
end
end

function assert_hasfields(T, fnames)
for fname in fnames
if !(fname in fieldnames(T))
Expand Down Expand Up @@ -187,15 +200,5 @@ end
)
end

@generated function setproperties(obj::NamedTuple, patch::NamedTuple)
# this function is only generated to force the following check
# at compile time
assert_hasfields(obj, fieldnames(patch))
Expr(:block,
Expr(:meta, :inline),
:(merge(obj, patch))
)
end


end # module
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ end
@inferred constructorof(AB{Int, Int})
@test constructorof(AB{Int, Int})(1, 2) === AB(1,2)
@test constructorof(AB{Int, Int})(1.0, 2) === AB(1.0,2)
@test constructorof(typeof((a=1, b=2)))(1.0, 2) === (a=1.0, b=2)
@test constructorof(NamedTuple{(:a, :b)})(1.0, 2) === (a=1.0, b=2)
@test constructorof(Tuple)(1.0, 2) === (1.0, 2)
@test constructorof(Tuple{Nothing, Missing})(1.0, 2) === (1.0, 2)
end

@testset "setproperties" begin
Expand Down

0 comments on commit bf245e2

Please sign in to comment.