diff --git a/spec/cbor/from_cbor_spec.cr b/spec/cbor/from_cbor_spec.cr index 2d1edde..fcb6bc2 100644 --- a/spec/cbor/from_cbor_spec.cr +++ b/spec/cbor/from_cbor_spec.cr @@ -1,5 +1,9 @@ require "../spec_helper" +enum TestEnum + Foo = 1 +end + describe "CBOR helpers on basic types" do describe "#from_cbor" do tests = [ @@ -32,6 +36,7 @@ describe "CBOR helpers on basic types" do # [1_i8, [2_i8, 3_i8], [4_i8, 5_i8]]}, {Hash(UInt8, UInt8), Bytes[0xa0], {} of UInt8 => UInt8}, {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| diff --git a/src/cbor/decoder.cr b/src/cbor/decoder.cr index 3a47ea7..03a24fd 100644 --- a/src/cbor/decoder.cr +++ b/src/cbor/decoder.cr @@ -82,7 +82,7 @@ class CBOR::Decoder end end - private def finish_token! + def finish_token! @current_token = @lexer.next_token end @@ -115,7 +115,7 @@ class CBOR::Decoder end end - private def unexpected_token(token, expected = nil) + def unexpected_token(token, expected = nil) message = "Unexpected token #{token.class}" message += " expected #{expected}" if expected raise ParseError.new(message) diff --git a/src/cbor/from_cbor.cr b/src/cbor/from_cbor.cr index c6767ec..62fcfb7 100644 --- a/src/cbor/from_cbor.cr +++ b/src/cbor/from_cbor.cr @@ -60,6 +60,19 @@ def Hash.new(decoder : CBOR::Decoder) hash 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 # specified by [Section 2.4.1 of RFC 7049][1]. #