Module: IOSTSdk::Models::Util::Serializer

Defined in:
lib/iost_sdk/models/util/serializer.rb

Class Method Summary collapse

Class Method Details

.array_to_bytes(arr, size_prefix = true) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/iost_sdk/models/util/serializer.rb', line 19

def self.array_to_bytes(arr, size_prefix=true)
  return int32_to_bytes(0) if !arr || arr.empty?

  data_bytes = arr.map do |elem|
    if elem.class.name == 'Integer'
      int64_to_bytes(elem)
    elsif elem.class.name == 'String'
      string_to_bytes(elem)
    elsif elem.class.name == 'Array'
      array_to_bytes(elem)
    elsif elem.class.name == 'Hash'
      hash_to_bytes(elem)
    elsif elem.respond_to?(:raw_data_bytes)
      raw_data_bytes = array_to_bytes(elem.raw_data_bytes, false)
      (int32_to_bytes(raw_data_bytes.size) + raw_data_bytes).flatten
    end
  end

  data_bytes.flatten!

  size_prefix ? int32_to_bytes(arr.size) + data_bytes : data_bytes
end

.hash_to_bytes(h) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/iost_sdk/models/util/serializer.rb', line 42

def self.hash_to_bytes(h)
  return int32_to_bytes(0) if !h || h.empty?

  # hash to array of key-value pairs, sorted by key
  key_value_pairs = h.sort.map { |k, v| [k.to_s, v] }.flatten
  int32_to_bytes(h.size) + array_to_bytes(key_value_pairs, false)
end

.int32_to_bytes(int32) ⇒ Object



7
8
9
# File 'lib/iost_sdk/models/util/serializer.rb', line 7

def self.int32_to_bytes(int32)
  [int32].pack('L>').unpack('C*')
end

.int64_to_bytes(int64) ⇒ Object



11
12
13
# File 'lib/iost_sdk/models/util/serializer.rb', line 11

def self.int64_to_bytes(int64)
  [int64].pack('Q>').unpack('C*')
end

.string_to_bytes(str) ⇒ Object



15
16
17
# File 'lib/iost_sdk/models/util/serializer.rb', line 15

def self.string_to_bytes(str)
  int32_to_bytes(str.size) + str.unpack('C*')
end