module GLib
  load_class :PtrArray

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

    attr_accessor :element_type

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

    def self.new type
      wrap(Lib.g_ptr_array_new).tap {|it|
        it.element_type = type}
    end

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

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

    # Re-implementation of the g_ptr_array_index macro
    def index idx
      sz = FFI.type_size :pointer
      ptr = @struct[:pdata].get_pointer(idx * sz)
      GirFFI::ArgHelper.cast_from_pointer(element_type, ptr)
    end

    def each
      @struct[:len].times.each do |idx|
        yield index(idx)
      end
    end
  end
end
