master
Karchnu 2020-11-26 06:52:12 +01:00
parent 4d4948418d
commit 0c8baf1ccd
1 changed files with 47 additions and 0 deletions

47
src/cbor/uuid.cr Normal file
View File

@ -0,0 +1,47 @@
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