Class: ELFTools::LazyArray

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/elftools/lazy_array.rb

Overview

A helper class for ELFTools easy to implement 'lazy loading' objects. Mainly used when loading sections, segments, and symbols.

Only #[] loads an element on demand, any other method of Array loads all elements before it operates.

Instance Method Summary collapse

Constructor Details

#initialize(size) {|i| ... } ⇒ LazyArray

Instantiate a ELFTools::LazyArray object.

Examples:

arr = LazyArray.new(10) { |i| p "calc #{i}"; i * i }
p arr[2]
# "calc 2"
# 4

p arr[3]
# "calc 3"
# 9

p arr[3]
# 9

Parameters:

  • size (Integer)

    The size of array.

Yield Parameters:

  • i (Integer)

    Needs the +i+-th element.

Yield Returns:

  • (Object)

    Value of the +i+-th element.



33
34
35
36
37
# File 'lib/elftools/lazy_array.rb', line 33

def initialize(size, &block)
  @array = Array.new(size)
  super(@array)
  @block = block
end

Instance Method Details

#[](i) ⇒ Object

To access elements like a normal array.

Elements are lazy loaded at the first time access it.

Parameters:

  • i (Integer)

    The index, negative index is not supported.

Returns:

  • (Object)

    The element, returned type is the return type of block given in #initialize. nil if i is out of bound.



49
50
51
52
53
# File 'lib/elftools/lazy_array.rb', line 49

def [](i)
  return nil unless i.between?(0, size - 1)

  @array[i] ||= @block.call(i)
end

#__getobj__Array

Loads all elements.

Called whenever a method other than #[] and #size is invoked, so that those methods operate on a fully loaded array.

Examples:

arr = LazyArray.new(3) { |i| i * i }
p arr.map { |v| v + 1 }
# [1, 2, 5]

Returns:

  • (Array)

    The loaded array.



75
76
77
78
# File 'lib/elftools/lazy_array.rb', line 75

def __getobj__
  @array.each_index { |i| self[i] }
  @array
end

#sizeInteger Also known as: length

The size of this array.

This method never loads any element.

Returns:



60
61
62
# File 'lib/elftools/lazy_array.rb', line 60

def size
  @array.size
end