Limit hash keys to certain types.

remotes/dev/pr-limiting-keys
Karchnu 2020-11-30 01:17:35 +01:00
parent b0c62f89c8
commit 78fb8c5154
2 changed files with 42 additions and 3 deletions

View File

@ -5,13 +5,21 @@ 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(HashKeyType, Type) |
Int8 | Int8 |
UInt8 | UInt8 |
Int16 | Int16 |

View File

@ -7,6 +7,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
@ -34,8 +62,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)