Class: Takagi::Serialization::CborSerializer

Inherits:
Base
  • Object
show all
Defined in:
lib/takagi/serialization/cbor_serializer.rb

Overview

CBOR serializer (RFC 8949)

Handles application/cbor content-format (code 60). Encodes Ruby objects to CBOR binary format and decodes CBOR to Ruby objects.

Uses Takagi’s built-in CBOR implementation for zero external dependencies.

Examples:

Encoding

serializer = CborSerializer.new
bytes = serializer.encode({ temp: 25 })  # => "\xA1dtemp\x18\x19"

Decoding

data = serializer.decode("\xA1dtemp\x18\x19")  # => { "temp" => 25 }

Instance Method Summary collapse

Methods inherited from Base

#name

Instance Method Details

#binary?Boolean

CBOR is a binary format

Returns:

  • (Boolean)

    true



87
88
89
# File 'lib/takagi/serialization/cbor_serializer.rb', line 87

def binary?
  true
end

#content_format_codeInteger

CoAP content-format code for CBOR

Returns:

  • (Integer)

    60 (RFC 7049)



80
81
82
# File 'lib/takagi/serialization/cbor_serializer.rb', line 80

def content_format_code
  CoAP::Registries::ContentFormat::CBOR
end

#content_typeString

MIME type for CBOR

Returns:

  • (String)

    ‘application/cbor’



73
74
75
# File 'lib/takagi/serialization/cbor_serializer.rb', line 73

def content_type
  'application/cbor'
end

#decode(bytes) ⇒ Object

Decode CBOR bytes to Ruby object

Examples:

Object decoding

decode(cbor_bytes)  # => { "temp" => 25 }

Array decoding

decode(cbor_bytes)  # => [1, 2, 3]

Parameters:

  • bytes (String)

    CBOR binary data

Returns:

  • (Object)

    Decoded Ruby object (Hash, Array, Integer, etc.)

Raises:



60
61
62
63
64
65
66
67
68
# File 'lib/takagi/serialization/cbor_serializer.rb', line 60

def decode(bytes)
  return nil if bytes.nil? || bytes.empty?

  CBOR::Decoder.decode(bytes)
rescue CBOR::DecodeError => e
  raise DecodeError, "CBOR decoding failed: #{e.message}"
rescue StandardError => e
  raise DecodeError, "CBOR decoding error: #{e.message}"
end

#encode(data) ⇒ String

Encode Ruby object to CBOR bytes

Examples:

Hash encoding

encode({ temp: 25 })  # => CBOR bytes

Array encoding

encode([1, 2, 3])  # => CBOR bytes

Supported types

- Integer (signed/unsigned, up to 64-bit)
- Float (64-bit IEEE 754)
- String (UTF-8)
- Array
- Hash
- true, false, nil
- Time (as timestamp)

Parameters:

  • data (Object)

    Ruby object to encode

Returns:

  • (String)

    CBOR binary string

Raises:



39
40
41
42
43
44
45
46
47
# File 'lib/takagi/serialization/cbor_serializer.rb', line 39

def encode(data)
  return ''.b if data.nil? || data == ''

  CBOR::Encoder.encode(data)
rescue CBOR::EncodeError => e
  raise EncodeError, "CBOR encoding failed: #{e.message}"
rescue StandardError => e
  raise EncodeError, "CBOR encoding error: #{e.message}"
end