~arestifo/crystal-cbor

8e80db47fa9c94e0d13ccb82d6eb35892956db25 — Karchnu 1 year, 8 months ago b0c62f8
Add decoding/encoding of UUID
3 files changed, 60 insertions(+), 0 deletions(-)

A spec/cbor_uuid.cr
M src/cbor/from_cbor.cr
M src/cbor/to_cbor.cr
A spec/cbor_uuid.cr => spec/cbor_uuid.cr +15 -0
@@ 0,0 1,15 @@
require "./spec_helper"

describe CBOR do
  describe "UUID" do
    it "UUID#to_cbor" do
      uuid = UUID.new "fc47eb8e-b13c-481e-863a-8f8c47a550f2"
      uuid.to_cbor.hexstring.should eq "50fc47eb8eb13c481e863a8f8c47a550f2"
    end

    it "UUID#from_cbor" do
      uuid = UUID.from_cbor "50fc47eb8eb13c481e863a8f8c47a550f2".hexbytes
      uuid.to_cbor.hexstring.should eq "50fc47eb8eb13c481e863a8f8c47a550f2"
    end
  end
end

M src/cbor/from_cbor.cr => src/cbor/from_cbor.cr +31 -0
@@ 1,3 1,5 @@
require "uuid"

def Object.from_cbor(string_or_io)
  parser = CBOR::Decoder.new(string_or_io)
  new(parser)


@@ 255,3 257,32 @@ def Union.new(decoder : CBOR::Decoder)
    {% end %}
  {% end %}
end

struct UUID
  # Creates UUID from CBOR using `CBOR::Decoder`.
  #
  # ```
  # require "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
end

M src/cbor/to_cbor.cr => src/cbor/to_cbor.cr +14 -0
@@ 1,3 1,5 @@
require "uuid"

class Object
  def to_cbor : Bytes
    encoder = CBOR::Encoder.new


@@ 130,3 132,15 @@ end
#   def to_cbor(encoder : CBOR::Encoder)
#   end
# end

struct UUID
  # Returns UUID as CBOR value.
  #
  # ```
  # uuid = UUID.new("87b3042b-9b9a-41b7-8b15-a93d3f17025e")
  # uuid.to_cbor
  # ```
  def to_cbor(cbor : CBOR::Encoder)
    cbor.write(@bytes.to_slice)
  end
end