Class: RLP::Sedes::CountableList

Inherits:
Object
  • Object
show all
Includes:
Error, Utils
Defined in:
lib/rlp/sedes/countable_list.rb

Overview

A sedes for lists of arbitrary length.

Instance Method Summary collapse

Methods included from Utils

#big_endian_to_int, #bytes_to_str, #encode_hex, #int_to_big_endian, #list?, make_immutable!, #primitive?, #str_to_bytes

Constructor Details

#initialize(element_sedes, max_length: nil) ⇒ CountableList

Returns a new instance of CountableList.


10
11
12
13
# File 'lib/rlp/sedes/countable_list.rb', line 10

def initialize(element_sedes, max_length: nil)
  @element_sedes = element_sedes
  @max_length = max_length
end

Instance Method Details

#deserialize(serial) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rlp/sedes/countable_list.rb', line 35

def deserialize(serial)
  raise ListDeserializationError.new(message: 'Can only deserialize sequences', serial: serial) unless list?(serial)

  result = []
  serial.each_with_index do |e, i|
    begin
      result.push @element_sedes.deserialize(e)
    rescue DeserializationError => e
      raise ListDeserializationError.new(serial: serial, element_exception: e, index: i)
    end

    if @max_length && result.size > @max_length
      msg = "Too many elements (#{result.size}, allowed #{@max_length})"
      raise ListDeserializationError.new(message: msg, serial: serial)
    end
  end

  result.freeze
end

#serialize(obj) ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rlp/sedes/countable_list.rb', line 15

def serialize(obj)
  raise ListSerializationError.new(message: "Can only serialize sequences", obj: obj) unless list?(obj)

  result = []
  obj.each_with_index do |e, i|
    begin
      result.push @element_sedes.serialize(e)
    rescue SerializationError => e
      raise ListSerializationError.new(obj: obj, element_exception: e, index: i)
    end

    if @max_length && result.size > @max_length
      msg = "Too many elements (#{result.size}, allowed #{@max_length})"
      raise ListSerializationError.new(message: msg, obj: obj)
    end
  end

  result
end