Class: Rlp::Sedes::List

Inherits:
Array
  • Object
show all
Defined in:
lib/rlp-lite/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.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rlp-lite/sedes/list.rb', line 12

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:



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rlp-lite/sedes/list.rb', line 49

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:



33
34
35
36
37
38
39
40
41
# File 'lib/rlp-lite/sedes/list.rb', line 33

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