Skip to content

Commit bac759c

Browse files
authored
convert to named tuple utility function (#53)
1 parent 49478a5 commit bac759c

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/interface.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,14 @@ tuple_type(::Type{NamedTuple{names, types}}) where {names, types} = types
1717
function fields(::Type{T}) where {T}
1818
fieldnames(staticschema(T))
1919
end
20+
21+
@generated function to_namedtuple(::Type{NT}, s::S) where {NT, S}
22+
names = fieldnames(NT)
23+
exprs = [Expr(:call, :getfieldindex, :s, QuoteNode(field), i) for (i, field) in enumerate(names)]
24+
tup = Expr(:call, :tuple, exprs...)
25+
:(NT($tup))
26+
end
27+
28+
function to_namedtuple(s::S) where S
29+
to_namedtuple(staticschema(S), s)
30+
end

test/runtests.jl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ using StructArrays: LazyRow
33
import Tables, PooledArrays, WeakRefStrings
44
using Test
55

6-
# write your own tests here
76
@testset "index" begin
87
a, b = [1 2; 3 4], [4 5; 6 7]
98
t = StructArray((a = a, b = b))
@@ -31,6 +30,13 @@ end
3130
@test isa(v_pooled.b, PooledArrays.PooledArray)
3231
end
3332

33+
@testset "namedtuple" begin
34+
@inferred StructArrays.to_namedtuple(1+2im)
35+
@test StructArrays.to_namedtuple(1+2im) == (re = 1, im = 2)
36+
@test StructArrays.to_namedtuple((a=1,)) == (a=1,)
37+
@test StructArrays.to_namedtuple((1, 2, :s)) == (x1=1, x2=2, x3=:s)
38+
end
39+
3440
@testset "permute" begin
3541
a = WeakRefStrings.StringVector(["a", "b", "c"])
3642
b = PooledArrays.PooledArray([1, 2, 3])

0 commit comments

Comments
 (0)