Class: Takagi::Serialization::TextSerializer

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

Overview

Text/plain serializer (RFC 2046)

Handles text/plain content-format (code 0). Simple UTF-8 text encoding/decoding.

Examples:

Encoding

serializer = TextSerializer.new
bytes = serializer.encode("Hello World")  # => "Hello World" (as UTF-8 bytes)

Decoding

text = serializer.decode(bytes)  # => "Hello World"

Instance Method Summary collapse

Methods inherited from Base

#name

Instance Method Details

#binary?Boolean

Text is not binary

Returns:

  • (Boolean)

    false



82
83
84
# File 'lib/takagi/serialization/text_serializer.rb', line 82

def binary?
  false
end

#content_format_codeInteger

CoAP content-format code for text/plain

Returns:

  • (Integer)

    0 (RFC 7252 §12.3)



75
76
77
# File 'lib/takagi/serialization/text_serializer.rb', line 75

def content_format_code
  CoAP::Registries::ContentFormat::TEXT_PLAIN
end

#content_typeString

MIME type for plain text

Returns:

  • (String)

    ‘text/plain’



68
69
70
# File 'lib/takagi/serialization/text_serializer.rb', line 68

def content_type
  'text/plain'
end

#decode(bytes) ⇒ String

Decode UTF-8 bytes to string

Examples:

Text decoding

decode(bytes)  # => "Hello World"

Parameters:

  • bytes (String)

    UTF-8 binary data

Returns:

  • (String)

    Decoded UTF-8 string

Raises:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/takagi/serialization/text_serializer.rb', line 49

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

  # Ensure UTF-8 encoding
  bytes.force_encoding('UTF-8')

  # Validate UTF-8
  unless bytes.valid_encoding?
    raise DecodeError, 'Invalid UTF-8 encoding'
  end

  bytes
rescue StandardError => e
  raise DecodeError, "Text decoding failed: #{e.message}"
end

#encode(data) ⇒ String

Encode object to UTF-8 text bytes

Examples:

String encoding

encode("hello")  # => "hello"

Number encoding

encode(42)  # => "42"

Object encoding

encode({ temp: 25 })  # => "{:temp=>25}"

Parameters:

  • data (Object)

    Object to encode (converted to string)

Returns:

  • (String)

    UTF-8 encoded binary string

Raises:



31
32
33
34
35
36
37
38
39
# File 'lib/takagi/serialization/text_serializer.rb', line 31

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

  data.to_s.encode('UTF-8').b
rescue Encoding::UndefinedConversionError => e
  raise EncodeError, "Text encoding failed (invalid UTF-8): #{e.message}"
rescue StandardError => e
  raise EncodeError, "Text encoding failed: #{e.message}"
end