Class: Klay::Rlp::Sedes::List

Inherits:
Array
  • Object
show all
Defined in:
lib/klay/rlp/sedes/list.rb

Overview

A sedes type for lists of fixed length.

Instance Method Summary collapse

Constructor Details

#initialize(elements: [], strict: true) ⇒ List

Create a serializable list of fixed size.

Parameters:

  • elements (Array) (defaults to: [])

    an array indicating the structure of the list.

  • strict (Boolean) (defaults to: true)

    an option to enforce the given structure.



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/klay/rlp/sedes/list.rb', line 33

def initialize(elements: [], strict: true)
  super()
  @strict = strict
  elements.each do |e|
    if Sedes.is_sedes?(e)
      push e
    elsif Util.is_list?(e)
      push List.new(elements: e)
    else
      raise TypeError, "Instances of List must only contain sedes objects or nested sequences thereof."
    end
  end
end

Instance Method Details

#deserialize(serial) ⇒ Array

Deserializes a list.

Parameters:

  • serial (Array)

    the serialized list.

Returns:

  • (Array)

    a deserialized list.

Raises:



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/klay/rlp/sedes/list.rb', line 69

def deserialize(serial)
  raise DeserializationError, "Can only deserialize sequences" unless Util.is_list?(serial)
  raise DeserializationError, "List has wrong length" if @strict && serial.size != self.size
  result = []
  len = [serial.size, self.size].min
  len.times do |i|
    sedes = self[i]
    element = serial[i]
    result.push sedes.deserialize(element)
  end
  result.freeze
end

#serialize(obj) ⇒ Array

Serialize an array.

Parameters:

  • obj (Array)

    the array to be serialized.

Returns:

  • (Array)

    a serialized list.

Raises:



53
54
55
56
57
58
59
60
61
# File 'lib/klay/rlp/sedes/list.rb', line 53

def serialize(obj)
  raise SerializationError, "Can only serialize sequences" unless Util.is_list?(obj)
  raise SerializationError, "List has wrong length" if (@strict && self.size != obj.size) || self.size < obj.size
  result = []
  obj.zip(self).each_with_index do |(element, sedes), i|
    result.push sedes.serialize(element)
  end
  result
end