File: ruby_closure.rb

package info (click to toggle)
ruby-gir-ffi 0.16.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 924 kB
  • sloc: ruby: 6,849; makefile: 4
file content (61 lines) | stat: -rw-r--r-- 1,470 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true

require "ffi-gobject/closure"

module GObject
  # Encapsulates Ruby blocks as GObject Closures.
  class RubyClosure < Closure
    # @api private
    BLOCK_STORE = {}

    # Extend the standard +GObject::Closure+ layout with a field block_id to store
    # the object_id of the associated block.
    #
    # @api private
    class Struct < GirFFI::Struct
      layout :parent, Closure::Struct, 0,
             :block_id, :int64
    end

    def initialize(&block)
      block or raise ArgumentError, "Block needed"

      initialize_simple(self.class::Struct.size, nil)
      self.block = block
      set_marshal proc { |*args| self.class.marshaller(*args) }
    end

    # @api private
    def self.marshaller(closure, return_value, param_values, _invocation_hint,
                        _marshal_data)
      # TODO: Improve by registering RubyClosure as a GObject type
      rclosure = wrap(closure.to_ptr)
      param_values ||= []

      args = param_values.map(&:get_value)

      result = rclosure.invoke_block(*args)

      return_value&.set_value(result)
    end

    # @api private
    # TODO: Re-structure so invoke_block can become a private method
    def invoke_block(*args)
      block.call(*args)
    end

    private

    # @api private
    def block=(block)
      id = block.object_id
      BLOCK_STORE[id] = block
      struct[:block_id] = id
    end

    def block
      BLOCK_STORE[struct[:block_id]]
    end
  end
end