From 0c8baf1ccd8e0ce6815ffb76957844f1d4977f22 Mon Sep 17 00:00:00 2001 From: Karchnu Date: Thu, 26 Nov 2020 06:52:12 +0100 Subject: [PATCH] UUID. --- src/cbor/uuid.cr | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/cbor/uuid.cr diff --git a/src/cbor/uuid.cr b/src/cbor/uuid.cr new file mode 100644 index 0000000..53c346d --- /dev/null +++ b/src/cbor/uuid.cr @@ -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