Add enum support

dev
Alberto Restifo 2020-04-25 17:33:19 +02:00
parent 6a70810667
commit 82882ba7a8
3 changed files with 20 additions and 2 deletions

View File

@ -1,5 +1,9 @@
require "../spec_helper" require "../spec_helper"
enum TestEnum
Foo = 1
end
describe "CBOR helpers on basic types" do describe "CBOR helpers on basic types" do
describe "#from_cbor" do describe "#from_cbor" do
tests = [ tests = [
@ -32,6 +36,7 @@ describe "CBOR helpers on basic types" do
# [1_i8, [2_i8, 3_i8], [4_i8, 5_i8]]}, # [1_i8, [2_i8, 3_i8], [4_i8, 5_i8]]},
{Hash(UInt8, UInt8), Bytes[0xa0], {} of UInt8 => UInt8}, {Hash(UInt8, UInt8), Bytes[0xa0], {} of UInt8 => UInt8},
{Hash(UInt8, UInt8), Bytes[0xa2, 0x01, 0x02, 0x03, 0x04], Hash(UInt8, UInt8){1 => 2, 3 => 4}}, {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},
] ]
tests.each do |tt| tests.each do |tt|

View File

@ -82,7 +82,7 @@ class CBOR::Decoder
end end
end end
private def finish_token! def finish_token!
@current_token = @lexer.next_token @current_token = @lexer.next_token
end end
@ -115,7 +115,7 @@ class CBOR::Decoder
end end
end end
private def unexpected_token(token, expected = nil) def unexpected_token(token, expected = nil)
message = "Unexpected token #{token.class}" message = "Unexpected token #{token.class}"
message += " expected #{expected}" if expected message += " expected #{expected}" if expected
raise ParseError.new(message) raise ParseError.new(message)

View File

@ -60,6 +60,19 @@ def Hash.new(decoder : CBOR::Decoder)
hash hash
end end
def Enum.new(decoder : CBOR::Decoder)
case token = decoder.current_token
when CBOR::Token::IntT
decoder.finish_token!
from_value(token.value)
when CBOR::Token::StringT
decoder.finish_token!
parse(token.value)
else
decoder.unexpected_token(token, "IntT or StringT")
end
end
# Reads the CBOR values as a time. The value must be surrounded by a time tag as # 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]. # specified by [Section 2.4.1 of RFC 7049][1].
# #