Class: GRX::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/grx/storage.rb

Overview

=================================================================== Storage — Native memory buffer

When CAPI is loaded:

@ptr  → Fiddle::Pointer to 32-byte aligned doubles block
      allocated via grx_alloc() (C posix_memalign / _aligned_malloc).
      Data lives in C heap, NOT managed by Ruby GC.

When CAPI is NOT loaded (fallback): @data → Standard Ruby Array (slow but correct).

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(array_plano) ⇒ Storage

Returns a new instance of Storage.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/grx/storage.rb', line 21

def initialize(array_plano)
  @size = array_plano.size

  if CAPI::LOADED
    # Fast mode: aligned C memory
    @ptr = CAPI.grx_alloc(@size)
    raise StorageError, "grx_alloc failed (OOM)" if @ptr.null?

    # Pack Ruby Array into C buffer as IEEE 754 doubles
    bytes = array_plano.pack("d*")
    @ptr[0, bytes.bytesize] = bytes

    # Finalizer releases C memory upon Ruby GC collection
    ptr_to_free = @ptr
    ObjectSpace.define_finalizer(self, self.class.make_finalizer(ptr_to_free))
  else
    # Fallback mode: Ruby Array
    @data = array_plano.map(&:to_f)
    @ptr  = nil
  end
end

Instance Attribute Details

#ptrObject (readonly)

Returns the value of attribute ptr.



19
20
21
# File 'lib/grx/storage.rb', line 19

def ptr
  @ptr
end

#sizeObject (readonly)

Returns the value of attribute size.



18
19
20
# File 'lib/grx/storage.rb', line 18

def size
  @size
end

Class Method Details

.make_finalizer(ptr) ⇒ Object



43
44
45
# File 'lib/grx/storage.rb', line 43

def self.make_finalizer(ptr)
  proc { CAPI.grx_free(ptr) }
end

Instance Method Details

#read(indice) ⇒ Object


Read / Write — used in fallback mode and by item/get() High-performance tensor ops operate directly on @ptr in C.



51
52
53
54
55
56
57
# File 'lib/grx/storage.rb', line 51

def read(indice)
  if CAPI::LOADED
    @ptr[indice * 8, 8].unpack1("d")
  else
    @data[indice]
  end
end

#to_ruby_arrayObject

Dumps entire buffer to a Ruby Array



68
69
70
71
72
73
74
# File 'lib/grx/storage.rb', line 68

def to_ruby_array
  if CAPI::LOADED
    @ptr[0, @size * 8].unpack("d#{@size}")
  else
    @data.dup
  end
end

#write(indice, valor) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/grx/storage.rb', line 59

def write(indice, valor)
  if CAPI::LOADED
    @ptr[indice * 8, 8] = [valor.to_f].pack("d")
  else
    @data[indice] = valor.to_f
  end
end