Class: RLP::LazyList

Inherits:
Object
  • Object
show all
Includes:
Enumerable, DecodeLazy
Defined in:
lib/rlp/lazy_list.rb

Overview

A RLP encoded list which decodes itself when necessary.

Both indexing with positive indices and iterating are supported. Getting the length is possible as well but requires full horizontal encoding.

Constant Summary

Constants included from Utils

Utils::BINARY_ENCODING

Constants included from Constant

Constant::BYTE_EMPTY, Constant::BYTE_ZERO, Constant::LIST_PREFIX_OFFSET, Constant::LONG_LENGTH_LIMIT, Constant::PRIMITIVE_PREFIX_OFFSET, Constant::SHORT_LENGTH_LIMIT

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DecodeLazy

#consume_item_lazy, #decode_lazy, #peek

Methods included from Decode

#decode

Methods included from Utils

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

Constructor Details

#initialize(rlp, start, next_start, sedes: nil, sedes_options: nil) ⇒ LazyList



27
28
29
30
31
32
33
34
35
36
# File 'lib/rlp/lazy_list.rb', line 27

def initialize(rlp, start, next_start, sedes: nil, sedes_options: nil)
  @rlp = rlp
  @start = start
  @next_start = next_start
  @index = start
  @elements = []
  @size = nil
  @sedes = sedes
  @sedes_options = sedes_options
end

Instance Attribute Details

#sedesObject

Returns the value of attribute sedes.



14
15
16
# File 'lib/rlp/lazy_list.rb', line 14

def sedes
  @sedes
end

#sedes_optionsObject

Returns the value of attribute sedes_options.



14
15
16
# File 'lib/rlp/lazy_list.rb', line 14

def sedes_options
  @sedes_options
end

Instance Method Details

#[](i) ⇒ Object



64
65
66
# File 'lib/rlp/lazy_list.rb', line 64

def [](i)
  fetch(i, nil)
end

#each(&block) ⇒ Object



59
60
61
62
# File 'lib/rlp/lazy_list.rb', line 59

def each(&block)
  @elements.each(&block)
  loop { block.call(next_item) }
end

#fetch(*args) ⇒ Object



68
69
70
71
72
73
74
75
76
77
# File 'lib/rlp/lazy_list.rb', line 68

def fetch(*args)
  i = args[0]

  loop do
    raise StopIteration if @elements.size > i
    next_item
  end

  @elements.fetch(*args)
end

#next_itemObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rlp/lazy_list.rb', line 38

def next_item
  if @index == @next_start
    @size = @elements.size
    raise StopIteration
  elsif @index < @next_start
    item, @index = consume_item_lazy @rlp, @index

    if @sedes
      # FIXME: lazy man's kwargs
      item = @sedes_options.empty? ?
               @sedes.deserialize(item) :
               @sedes.deserialize(item, **@sedes_options)
    end

    @elements.push item
    item
  else
    raise "Assertion failed: index cannot be larger than next start"
  end
end

#sizeObject Also known as: length



79
80
81
82
83
84
# File 'lib/rlp/lazy_list.rb', line 79

def size
  unless @size
    loop { next_item }
  end
  @size
end