crystal-cbor/src/cbor/uuid.cr

48 lines
1.1 KiB
Crystal

require "../cbor"
require "uuid"
struct UUID
# Creates UUID from CBOR using `CBOR::Decoder`.
#
# NOTE: `require "uuid/cbor"` is required to opt-in to this feature.
#
# ```
# require "cbor"
# require "uuid"
# require "uuid/cbor"
#
# class Example
# include CBOR::Serializable
#
# property id : UUID
# end
#
# hash = {"id" => "ba714f86-cac6-42c7-8956-bcf5105e1b81"}
# example = Example.from_cbor hash.to_cbor
# example.id # => UUID(ba714f86-cac6-42c7-8956-bcf5105e1b81)
# ```
def self.new(pull : CBOR::Decoder)
# Either the UUID was encoded as String or bytes (smaller).
case pull.current_token
when CBOR::Token::StringT
new(pull.read_string)
when CBOR::Token::BytesT
new(pull.read_bytes)
else
raise "trying to get an UUID, but CBOR value isn't a string nor bytes: #{pull.current_token}"
end
end
# Returns UUID as CBOR value.
#
# NOTE: `require "uuid/cbor"` is required to opt-in to this feature.
#
# ```
# uuid = UUID.new("87b3042b-9b9a-41b7-8b15-a93d3f17025e")
# uuid.to_cbor
# ```
def to_cbor(cbor : CBOR::Encoder)
cbor.write(@bytes.to_slice)
end
end