Class: ArrayType::Proxy

Inherits:
Object
  • Object
show all
Extended by:
AttrPublicReadPrivateWrite
Defined in:
lib/0xfacet/typed/array_type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from AttrPublicReadPrivateWrite

attr_public_read_private_write

Constructor Details

#initialize(initial_value = [], value_type:, initial_length: nil, on_change: nil) ⇒ Proxy

Returns a new instance of Proxy.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/0xfacet/typed/array_type.rb', line 24

def initialize(
  initial_value = [],
  value_type:,
  initial_length: nil,
  on_change: nil
)
  unless value_type.is_value_type?
    raise VariableTypeError.new("Only value types can me array elements")
  end
  
  self.value_type = value_type
  self.data = initial_value
  
  if initial_length
    amount_to_pad = initial_length - data.size
    
    amount_to_pad.times do
      data << TypedVariable.create(value_type) 
    end
  end
  
  self.on_change = on_change
end

Instance Attribute Details

#on_changeObject

Returns the value of attribute on_change.



14
15
16
# File 'lib/0xfacet/typed/array_type.rb', line 14

def on_change
  @on_change
end

Instance Method Details

#==(other) ⇒ Object



17
18
19
20
21
22
# File 'lib/0xfacet/typed/array_type.rb', line 17

def ==(other)
  return false unless other.is_a?(self.class)
  
  other.value_type == value_type &&
  other.data == data
end

#[](index) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/0xfacet/typed/array_type.rb', line 48

def [](index)
  index_var = TypedVariable.create_or_validate(:uint256, index, on_change: on_change)
  
  raise "Index out of bounds" if index_var >= data.size

  value = data[index_var]
  value || TypedVariable.create_or_validate(value_type, on_change: on_change)
end

#[]=(index, value) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/0xfacet/typed/array_type.rb', line 57

def []=(index, value)
  index_var = TypedVariable.create_or_validate(:uint256, index, on_change: on_change)
  
  raise "Sparse arrays are not supported" if index_var > data.size

  old_value = self.data[index_var]
  val_var = TypedVariable.create_or_validate(value_type, value, on_change: on_change)
  
  if old_value != val_var
    on_change&.call
    self.data[index_var] ||= val_var
    self.data[index_var].value = val_var.value
  end
end

#lengthObject



85
86
87
# File 'lib/0xfacet/typed/array_type.rb', line 85

def length
  data.length
end

#popObject



79
80
81
82
83
# File 'lib/0xfacet/typed/array_type.rb', line 79

def pop
  on_change&.call
  
  data.pop
end

#push(value) ⇒ Object



72
73
74
75
76
77
# File 'lib/0xfacet/typed/array_type.rb', line 72

def push(value)
  next_index = data.size
  
  self.[]=(next_index, value)
  nil
end