Skip to content

Commit

Permalink
Base.setindex for NamedProperties
Browse files Browse the repository at this point in the history
  • Loading branch information
Tokazama committed Sep 24, 2022
1 parent ee52a21 commit d127a79
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/PropertyDicts.jl
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ end

const NamedProperties{syms,T<:Tuple,V} = PropertyDict{Symbol,V,NamedTuple{syms,T}}

@inline function Base.setindex(npd::NamedProperties{syms}, v, key::Symbol) where {syms}
nt = getfield(npd, :d)
idx = Base.fieldindex(typeof(nt), key, false)
if idx === 0
return PropertyDict(NamedTuple{(syms..., key)}((values(nt)..., v)))
else
return PropertyDict(NamedTuple{syms}(ntuple(i -> idx === i ? v : getfield(nt, i), Val{nfields(syms)}())))
end
end

Base.IteratorSize(@nospecialize T::Type{<:PropertyDict}) = Base.IteratorSize(fieldtype(T, :d))
Base.IteratorEltype(@nospecialize T::Type{<:PropertyDict}) = Base.IteratorEltype(eltype(T))

Expand Down
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,9 @@ end
@test @inferred(mergewith(combiner, a, b, c, PropertyDict())) ==
PropertyDict((a = "1 and 1", b = "2 and 4 and 2", c = 3, d = 5))
end

@testset "setindex" begin
npd = Base.setindex(Base.setindex(PropertyDict(), 1, :x), 2, :y)
@test values(npd) == (1, 2)
@test keys(npd) == (:x, :y)
end

0 comments on commit d127a79

Please sign in to comment.