2020-04-20 14:57:20 +02:00
|
|
|
require "./lexer"
|
|
|
|
require "./token"
|
|
|
|
|
|
|
|
# Reads a CBOR input into a diagnostic string.
|
|
|
|
# This consumes the IO and is mostly usedful to tests again the example
|
|
|
|
# provided in the RFC and ensuring a correct functioning of the `CBOR::Lexer`.
|
|
|
|
class CBOR::Diagnostic
|
|
|
|
@lexer : Lexer
|
|
|
|
|
|
|
|
def initialize(input)
|
|
|
|
@lexer = Lexer.new(input)
|
|
|
|
end
|
|
|
|
|
|
|
|
# Reads the content of the IO and prints out a diagnostic string
|
|
|
|
# represation of the input.
|
|
|
|
def to_s : String
|
|
|
|
result = ""
|
2020-04-21 15:02:31 +02:00
|
|
|
while value = next_value
|
2020-04-21 22:48:27 +02:00
|
|
|
result += value
|
2020-04-20 14:57:20 +02:00
|
|
|
end
|
|
|
|
result
|
2020-04-19 20:40:10 +02:00
|
|
|
end
|
|
|
|
|
2020-04-20 14:57:20 +02:00
|
|
|
private def next_value : String?
|
2020-04-21 15:02:31 +02:00
|
|
|
token = @lexer.read_next
|
2020-04-20 14:57:20 +02:00
|
|
|
return nil unless token
|
|
|
|
|
2020-04-21 15:02:31 +02:00
|
|
|
case token[:kind]
|
2020-04-21 22:48:27 +02:00
|
|
|
when Kind::Int
|
|
|
|
token[:value].to_s
|
2020-04-21 23:18:56 +02:00
|
|
|
when Kind::String
|
|
|
|
%("#{token[:value].as(String)}")
|
2020-04-21 22:48:27 +02:00
|
|
|
when Kind::Bytes
|
|
|
|
"h'#{token[:value].as(Bytes).hexstring}'"
|
2020-04-21 15:02:31 +02:00
|
|
|
when Kind::BytesArray
|
2020-04-21 22:48:27 +02:00
|
|
|
token[:value].as(BytesArray).to_diagnostic
|
2020-04-21 00:01:35 +02:00
|
|
|
else
|
2020-04-21 22:48:27 +02:00
|
|
|
token[:kind].to_s
|
2020-04-19 20:40:10 +02:00
|
|
|
end
|
2020-04-20 14:57:20 +02:00
|
|
|
end
|
2020-04-19 20:40:10 +02:00
|
|
|
end
|