Add named tuple support

dev
Alberto Restifo 2020-04-25 18:13:56 +02:00
parent fbf74630b2
commit 14c52208a3
2 changed files with 27 additions and 0 deletions

View File

@ -38,6 +38,7 @@ describe "CBOR helpers on basic types" do
{Hash(UInt8, UInt8), Bytes[0xa2, 0x01, 0x02, 0x03, 0x04], Hash(UInt8, UInt8){1 => 2, 3 => 4}},
{TestEnum, Bytes[0x1a, 0x00, 0x00, 0x00, 0x01], TestEnum::Foo},
{Tuple(Int8, Int8), Bytes[0x82, 0x01, 0x02], {1_i8, 2_i8}},
{NamedTuple(a: UInt8, b: Array(UInt8)), Bytes[0xa2, 0x61, 0x61, 0x01, 0x61, 0x62, 0x82, 0x02, 0x03], {a: 1_u8, b: [2_u8, 3_u8]}},
]
tests.each do |tt|

View File

@ -99,6 +99,32 @@ def Tuple.new(decoder : CBOR::Decoder)
{% end %}
end
def NamedTuple.new(decoder : CBOR::Decoder)
{% begin %}
{% for key in T.keys %}
%var{key.id} = nil
{% end %}
decoder.consume_hash do
key = decoder.read_string
case key
{% for key, type in T %}
when {{key.stringify}}
%var{key.id} = {{type}}.new(decoder)
{% end %}
else
raise CBOR::ParseError.new("Missing attribute: #{key}")
end
end
{
{% for key, type in T %}
{{key}}: %var{key.id}.as({{type}}),
{% end %}
}
{% end %}
end
# Reads the CBOR values as a time. The value must be surrounded by a time tag as
# specified by [Section 2.4.1 of RFC 7049][1].
#