Skip to content

Commit

Permalink
support non-tuple propertynames
Browse files Browse the repository at this point in the history
  • Loading branch information
aplavin committed Jul 15, 2023
1 parent 39a5daf commit 33099cc
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "ConstructionBase"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
authors = ["Takafumi Arakaki", "Rafael Schouten", "Jan Weidner"]
version = "1.5.2"
version = "1.5.3"

[deps]
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Expand Down
19 changes: 12 additions & 7 deletions src/ConstructionBase.jl
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,20 @@ else
end
end

# names are consecutive integers: return tuple
# names are symbols: return namedtuple
# names are empty (object has no properties): also return namedtuple, for backwards compat and generally makes more sense
# dispatch on eltype(names) to select Tuple vs NamedTuple
@inline tuple_or_ntuple(names, vals) = tuple_or_ntuple(eltype(names), names, vals)
# if names are empty (object has no properties): return namedtuple, for backwards compat and generally makes more sense than tuple
@inline tuple_or_ntuple(names::Tuple{}, vals::Tuple) = NamedTuple{names}(vals)
@inline tuple_or_ntuple(names::Tuple{Vararg{Symbol}}, vals::Tuple) = NamedTuple{names}(vals)
@inline function tuple_or_ntuple(names::Tuple{Vararg{Int}}, vals::Tuple)
@assert names === ntuple(identity, length(names))
vals

# names are consecutive integers: return tuple
@inline function tuple_or_ntuple(::Type{Int}, names, vals)
@assert Tuple(names) == ntuple(identity, length(names))
Tuple(vals)
end
# names are symbols: return namedtuple
@inline tuple_or_ntuple(::Type{Symbol}, names, vals) = NamedTuple{Tuple(names)}(vals)
# otherwise: throw an error
tuple_or_ntuple(::Type, names, vals) = error("Only Int and Symbol propertynames are supported")

if VERSION >= v"1.7"
function getproperties(obj)
Expand Down
9 changes: 9 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,15 @@ if VERSION >= v"1.7"
@test getproperties(SProp((1, 2))) === ("pi1", "pi2")
# what should it return?
@test_broken getproperties(SProp(("a", "b")))

@test_throws ErrorException getproperties(SProp((1, :a)))
end

@testset "propertynames can be a vector" begin
@test getproperties(SProp([:a, :b])) === (a="psa", b="psb")
@test getproperties(SProp(Symbol[])) === (;)
@test getproperties(SProp([1, 2])) === ("pi1", "pi2")
@test getproperties(SProp(Int[])) === ()
end
end

Expand Down

0 comments on commit 33099cc

Please sign in to comment.