Class: Takagi::CBOR::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/takagi/cbor/encoder.rb

Overview

CBOR Encoder (RFC 8949)

Encodes Ruby objects to CBOR binary format. Optimized for IoT/CoAP workloads with minimal footprint.

Supported types:

  • Integers (signed/unsigned, up to 64-bit)

  • Floats (64-bit IEEE 754)

  • Strings (UTF-8)

  • Byte strings (binary data)

  • Arrays

  • Hashes (maps)

  • Booleans (true/false)

  • nil (null)

  • Time (timestamp, tag 1)

Examples:

Basic encoding

Encoder.encode({ temperature: 25.5, humidity: 60 })
# => "\xA2ktempera..." (CBOR bytes)

Encoding with symbols

Encoder.encode({ temp: 25.5 })
# Symbols converted to strings

Constant Summary collapse

MAJOR_TYPE_UNSIGNED_INT =

CBOR Major Types (RFC 8949 §3)

0
MAJOR_TYPE_NEGATIVE_INT =
1
MAJOR_TYPE_BYTE_STRING =
2
MAJOR_TYPE_TEXT_STRING =
3
MAJOR_TYPE_ARRAY =
4
MAJOR_TYPE_MAP =
5
MAJOR_TYPE_TAG =
6
MAJOR_TYPE_SIMPLE =
7
SIMPLE_FALSE =

Simple values (RFC 8949 §3.3)

20
SIMPLE_TRUE =
21
SIMPLE_NULL =
22
SIMPLE_FLOAT64 =
27
TAG_EPOCH_TIMESTAMP =

Tag values (RFC 8949 §3.4)

1
MAX_UINT8 =

Maximum safe integer values

0xFF
MAX_UINT16 =
0xFFFF
MAX_UINT32 =
0xFFFFFFFF
MAX_UINT64 =
0xFFFFFFFFFFFFFFFF
TYPE_HANDLERS =
{
  Integer => :encode_integer,
  Float => :encode_float,
  String => :encode_string,
  Array => :encode_array,
  Hash => :encode_map,
  TrueClass => :encode_simple,
  FalseClass => :encode_simple,
  NilClass => :encode_simple,
  Time => :encode_timestamp
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.encode(obj) ⇒ String

Encode a Ruby object to CBOR bytes

Examples:

Encoder.encode(42)              # => "\x18\x2A"
Encoder.encode("hello")         # => "ehello"
Encoder.encode([1, 2, 3])       # => "\x83\x01\x02\x03"
Encoder.encode({ a: 1 })        # => "\xA1aa\x01"

Parameters:

  • obj (Object)

    Ruby object to encode

Returns:

  • (String)

    CBOR-encoded binary string

Raises:



78
79
80
# File 'lib/takagi/cbor/encoder.rb', line 78

def encode(obj)
  new.encode(obj)
end

Instance Method Details

#encode(obj) ⇒ String

Encode a Ruby object to CBOR bytes

Parameters:

  • obj (Object)

    Ruby object to encode

Returns:

  • (String)

    CBOR-encoded binary string

Raises:



88
89
90
# File 'lib/takagi/cbor/encoder.rb', line 88

def encode(obj)
  encode_value(obj)
end