Class: Peruby::PerlArray

Inherits:
Object
  • Object
show all
Defined in:
lib/peruby/runtime/perl_array.rb

Overview

Perl AV represented as an array of mutable scalar cells.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cells = []) ⇒ PerlArray

Returns a new instance of PerlArray.



8
9
10
# File 'lib/peruby/runtime/perl_array.rb', line 8

def initialize(cells = [])
  @cells = cells
end

Instance Attribute Details

#cellsObject (readonly)

Returns the value of attribute cells.



6
7
8
# File 'lib/peruby/runtime/perl_array.rb', line 6

def cells
  @cells
end

Instance Method Details

#delete(index) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/peruby/runtime/perl_array.rb', line 32

def delete(index)
  index = normalize(index.to_i)
  return nil if index.negative? || index >= @cells.length

  value = @cells[index]&.get
  @cells[index] = nil
  @cells.pop while @cells.last.nil?
  value
end

#exists?(index) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
# File 'lib/peruby/runtime/perl_array.rb', line 27

def exists?(index)
  index = normalize(index.to_i)
  index >= 0 && index < @cells.length && !@cells[index].nil?
end

#fetch(index) ⇒ Object



12
13
14
15
16
17
# File 'lib/peruby/runtime/perl_array.rb', line 12

def fetch(index)
  index = normalize(index)
  return nil if index.negative?

  @cells[index]&.get
end

#last_indexObject



55
56
57
# File 'lib/peruby/runtime/perl_array.rb', line 55

def last_index
  size - 1
end

#last_index=(index) ⇒ Object

Raises:



59
60
61
62
63
64
65
# File 'lib/peruby/runtime/perl_array.rb', line 59

def last_index=(index)
  raise PerlError, 'Modification of non-creatable array value' if index < -1

  target_size = index + 1
  target_size < size ? @cells.slice!(target_size..) : @cells.fill(nil, size...target_size)
  index
end

#listObject



46
47
48
49
50
51
52
53
# File 'lib/peruby/runtime/perl_array.rb', line 46

def list
  @cells.each_index.map do |index|
    @cells[index] || begin
      cell = Scalar.new { @cells[index] = cell }
      cell
    end
  end
end

#replace_cell(index, cell) ⇒ Object

Raises:



67
68
69
70
71
72
73
# File 'lib/peruby/runtime/perl_array.rb', line 67

def replace_cell(index, cell)
  index = normalize(index)
  raise PerlError, 'Modification of non-creatable array value' if index.negative?

  @cells.fill(nil, size...index)
  @cells[index] = cell
end

#sizeObject



42
43
44
# File 'lib/peruby/runtime/perl_array.rb', line 42

def size
  @cells.size
end

#slot(index) ⇒ Object

Raises:



19
20
21
22
23
24
25
# File 'lib/peruby/runtime/perl_array.rb', line 19

def slot(index)
  index = normalize(index)
  raise PerlError, 'Modification of non-creatable array value' if index.negative?

  @cells.fill(nil, @cells.length...index)
  @cells[index] ||= Scalar.new
end