Limiting the hash key types to integers, floats, bool, string, bytes.
parent
678494cec9
commit
c292476cef
21
src/cbor.cr
21
src/cbor.cr
|
@ -5,13 +5,32 @@ require "./cbor/**"
|
||||||
module CBOR
|
module CBOR
|
||||||
VERSION = "0.1.0"
|
VERSION = "0.1.0"
|
||||||
|
|
||||||
|
# Represents CBOR Hash Keys: everything except Nil, hashs, arrays.
|
||||||
|
alias HashKeyType = Int8 | Int16 | Int32 | Int64 | Int128 |
|
||||||
|
UInt8 | UInt16 | UInt32 | UInt64 |
|
||||||
|
Float32 | Float64 |
|
||||||
|
String |
|
||||||
|
Bool |
|
||||||
|
Bytes
|
||||||
|
|
||||||
# Represents CBOR types
|
# Represents CBOR types
|
||||||
alias Type = Nil |
|
alias Type = Nil |
|
||||||
Bool |
|
Bool |
|
||||||
String |
|
String |
|
||||||
Bytes |
|
Bytes |
|
||||||
Array(Type) |
|
Array(Type) |
|
||||||
Hash(Type, Type) |
|
# Hash(Int8, Type) |
|
||||||
|
# Hash(Int16, Type) |
|
||||||
|
# Hash(Int32, Type) |
|
||||||
|
# Hash(Int64, Type) |
|
||||||
|
# Hash(UInt8, Type) |
|
||||||
|
# Hash(UInt16, Type) |
|
||||||
|
# Hash(UInt32, Type) |
|
||||||
|
# Hash(UInt64, Type) |
|
||||||
|
# Hash(Float32, Type) |
|
||||||
|
# Hash(Float64, Type) |
|
||||||
|
# Hash(String, Type) |
|
||||||
|
Hash(HashKeyType, Type) |
|
||||||
Int8 |
|
Int8 |
|
||||||
UInt8 |
|
UInt8 |
|
||||||
Int16 |
|
Int16 |
|
||||||
|
|
|
@ -20,6 +20,34 @@ class CBOR::Decoder
|
||||||
@current_token = @lexer.next_token
|
@current_token = @lexer.next_token
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# This is similar to read_value but with a focus on a key for a hash.
|
||||||
|
def read_key : HashKeyType
|
||||||
|
v = case token = @current_token
|
||||||
|
when Token::StringT
|
||||||
|
finish_token!
|
||||||
|
token.value.as(String)
|
||||||
|
when Token::IntT
|
||||||
|
finish_token!
|
||||||
|
token.value
|
||||||
|
when Token::FloatT
|
||||||
|
finish_token!
|
||||||
|
token.value
|
||||||
|
when Token::BytesT
|
||||||
|
finish_token!
|
||||||
|
token.value.as(Bytes)
|
||||||
|
when Token::SimpleValueT
|
||||||
|
finish_token!
|
||||||
|
token.value.to_t
|
||||||
|
else
|
||||||
|
puts "hash key with a #{token.class.to_s} value"
|
||||||
|
unexpected_token(token)
|
||||||
|
end
|
||||||
|
if v.nil?
|
||||||
|
raise ""
|
||||||
|
end
|
||||||
|
v
|
||||||
|
end
|
||||||
|
|
||||||
def read_value : Type
|
def read_value : Type
|
||||||
case token = @current_token
|
case token = @current_token
|
||||||
when Token::TagT
|
when Token::TagT
|
||||||
|
@ -47,8 +75,11 @@ class CBOR::Decoder
|
||||||
arr
|
arr
|
||||||
when Token::MapT
|
when Token::MapT
|
||||||
finish_token!
|
finish_token!
|
||||||
map = Hash(Type, Type).new
|
map = Hash(HashKeyType, Type).new
|
||||||
consume_sequence(token.size) { map[read_value] = read_value }
|
consume_sequence(token.size) {
|
||||||
|
key = read_key
|
||||||
|
map[key] = read_value
|
||||||
|
}
|
||||||
map
|
map
|
||||||
else
|
else
|
||||||
unexpected_token(token)
|
unexpected_token(token)
|
||||||
|
|
Loading…
Reference in New Issue