Class: BinaryCodec::STObject

Inherits:
SerializedType show all
Defined in:
lib/binary-codec/types/st_object.rb

Constant Summary collapse

OBJECT_END_MARKER_BYTE =
[225]
OBJECT_END_MARKER =
'ObjectEndMarker'.freeze
ST_OBJECT =
'STObject'.freeze
DESTINATION =
'Destination'.freeze
ACCOUNT =
'Account'.freeze
SOURCE_TAG =
'SourceTag'.freeze
DEST_TAG =
'DestinationTag'.freeze

Instance Attribute Summary

Attributes inherited from SerializedType

#bytes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from SerializedType

from, from_bytes, from_hex, from_json, get_type_by_name, #to_byte_sink, #to_bytes, #to_hex, #to_s

Constructor Details

#initialize(byte_buf = nil) ⇒ STObject

attr_reader :type, :bytes



14
15
16
# File 'lib/binary-codec/types/st_object.rb', line 14

def initialize(byte_buf = nil)
  @bytes = byte_buf || Array.new(0)
end

Class Method Details

.from_parser(parser, size_hint = nil) ⇒ STObject

Construct a STObject from a BinaryParser

Parameters:

  • parser (BinaryParser)

    BinaryParser to read STObject from

  • size_hint (Integer) (defaults to: nil)

    Optional size hint for the object

Returns:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/binary-codec/types/st_object.rb', line 23

def self.from_parser(parser, size_hint = nil)
  list = BytesList.new
  bytes = BinarySerializer.new(list)

  until parser.end?
    field = parser.read_field

    break if field.name == OBJECT_END_MARKER

    associated_value = parser.read_field_value(field)

    bytes.write_field_and_value(field, associated_value)
    bytes.put(OBJECT_END_MARKER_BYTE) if field.type == ST_OBJECT
  end

  STObject.new(list.to_bytes)
end

Instance Method Details

#to_jsonString

Method to get the JSON interpretation of self.bytes

Returns:

  • (String)

    A stringified JSON object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/binary-codec/types/st_object.rb', line 44

def to_json()
  parser = BinaryParser.new(to_s)
  accumulator = {}

  until parser.end?
    field = parser.read_field
    break if field.name == OBJECT_END_MARKER # Break if the object end marker is reached
    value = parser.read_field_value(field).to_json
    value = JSON.parse(value) if field.type == ST_OBJECT || field.type == Amount
    accumulator[field.name] = value
  end

  JSON.generate(accumulator)
end