Sha256: 3dd017ad6ce7ba5aad2c66ebd5abda4a056a27431b06792b50076399bd668675

Contents?: true

Size: 1.99 KB

Versions: 10

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

require "ffi-glib/container_class_methods"
require "gir_ffi/array_element_convertor"

GLib.load_class :PtrArray

module GLib
  # Overrides for GPtrArray, GLib's automatically growing array of
  # pointers.
  class PtrArray
    include Enumerable
    extend ContainerClassMethods

    attr_reader :element_type

    POINTER_SIZE = FFI.type_size(:pointer)

    class << self
      # Remove stub generated by builder.
      remove_method :add if method_defined? :add
    end

    def initialize(type)
      @element_type = type
      store_pointer Lib.g_ptr_array_new
    end

    def self.from_enumerable(type, arr)
      new(type).tap { |it| it.add_array arr }
    end

    def self.add(array, data)
      array.add data
    end

    def reset_typespec(typespec)
      @element_type = typespec
      self
    end

    def add(data)
      ptr = GirFFI::InPointer.from element_type, data
      Lib.g_ptr_array_add self, ptr
    end

    def add_array(ary)
      ary.each { |item| add item }
    end

    # Re-implementation of the g_ptrarray_index macro
    def index(idx)
      unless (0...length).cover? idx
        raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}"
      end

      item_ptr = data_ptr + idx * element_size

      convert_element_type = case element_type
                             when :utf8
                               :utf8
                             when GirFFI::ObjectBase
                               element_type
                             else
                               [:pointer, element_type]
                             end

      convertor = GirFFI::ArrayElementConvertor.new convert_element_type, item_ptr
      convertor.to_ruby_value
    end

    def each
      length.times do |idx|
        yield index(idx)
      end
    end

    def length
      struct[:len]
    end

    def ==(other)
      to_a == other.to_a
    end

    private

    def element_size
      POINTER_SIZE
    end

    def data_ptr
      struct[:pdata]
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
gir_ffi-0.15.9 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.8 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.7 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.6 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.5 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.4 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.3 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.2 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.1 lib/ffi-glib/ptr_array.rb
gir_ffi-0.15.0 lib/ffi-glib/ptr_array.rb