crystal-cbor/src/cbor/diagnostic.cr

44 lines
1.0 KiB
Crystal
Raw Normal View History

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
end
result
end
private def next_value : String?
2020-04-21 15:02:31 +02:00
token = @lexer.read_next
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-22 09:33:46 +02:00
when Kind::StringArray
token[:value].as(StringArray).to_diagnostic
2020-04-21 00:01:35 +02:00
else
2020-04-21 22:48:27 +02:00
token[:kind].to_s
end
end
end