Sha256: 98d944e95107f420a6bfe69b4d5bdd1f553ebc64198b1954024b71755b06319e

Contents?: true

Size: 1.42 KB

Versions: 9

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true
module GirFFI
  # Represents a null-terminated array.
  class ZeroTerminated
    include Enumerable

    attr_reader :element_type

    def initialize(elm_t, ptr)
      @element_type = elm_t
      @ptr = ptr
    end

    def to_ptr
      @ptr
    end

    def self.from(type, arg)
      new type, InPointer.from_array(type, arg)
    end

    def self.wrap(type, arg)
      new type, arg
    end

    def each
      return if @ptr.null?
      offset = 0
      while (val = read_value(offset))
        offset += ffi_type_size
        yield wrap_value(val)
      end
    end

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

    private

    def read_value(offset)
      val = fetch_value(offset)
      val unless val.zero?
    end

    def getter_method
      @getter_method ||= "get_#{ffi_type}"
    end

    def fetch_value(offset)
      case ffi_type
      when Module
        ffi_type.get_value_from_pointer(@ptr, offset)
      when Symbol
        @ptr.send(getter_method, offset)
      else
        raise NotImplementedError
      end
    end

    def wrap_value(val)
      case element_type
      when Array
        element_type.last.wrap val
      when Class
        element_type.wrap val
      else
        val
      end
    end

    def ffi_type
      @ffi_type ||= TypeMap.type_specification_to_ffi_type element_type
    end

    def ffi_type_size
      @ffi_type_size ||= FFI.type_size(ffi_type)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
gir_ffi-0.11.1 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.11.0 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.10.2 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.10.1 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.10.0 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.10.0.pre1 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.9.5 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.9.4 lib/gir_ffi/zero_terminated.rb
gir_ffi-0.9.3 lib/gir_ffi/zero_terminated.rb