Sha256: 837be2732ee4de199770e652ca523d6e74a51cccdeabd24ab5dead60efb1a67c

Contents?: true

Size: 1.84 KB

Versions: 4

Compression:

Stored size: 1.84 KB

Contents

# frozen_string_literal: true

module GirFFI
  module Builders
    # Builder that generates code to convert values from C to Ruby. Used by
    # argument builders.
    class CToRubyConvertor
      def initialize(type_info, argument, length_arg, ownership_transfer: nil)
        @type_info = type_info
        @argument = argument
        @length_arg = length_arg
        @ownership_transfer = ownership_transfer
      end

      def conversion
        case @type_info.flattened_tag
        when :utf8, :filename
          if @ownership_transfer == :everything
            "GirFFI::AllocationHelper.free_after #{@argument}, &:to_utf8"
          else
            "#{@argument}.to_utf8"
          end
        when :object
          base = "#{@type_info.argument_class_name}.wrap(#{conversion_argument_list})"
          @ownership_transfer == :nothing ? "#{base}.tap { |it| it && it.ref }" : base
        else
          "#{argument_class}.#{conversion_method}(#{conversion_argument_list})"
        end
      end

      private

      def conversion_method
        case @type_info.flattened_tag
        when :struct, :union
          case @ownership_transfer
          when :everything
            'wrap_own'
          when :nothing
            'wrap_copy'
          else
            'wrap'
          end
        else
          'wrap'
        end
      end

      def conversion_argument_list
        conversion_arguments.join(', ')
      end

      def conversion_arguments
        case @type_info.flattened_tag
        when :c
          [@type_info.element_type.inspect, array_size, @argument]
        else
          @type_info.extra_conversion_arguments.map(&:inspect).push(@argument)
        end
      end

      def array_size
        @length_arg || @type_info.array_fixed_size
      end

      def argument_class
        @type_info.argument_class_name
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
gir_ffi-0.14.1 lib/gir_ffi/builders/c_to_ruby_convertor.rb
gir_ffi-0.14.0 lib/gir_ffi/builders/c_to_ruby_convertor.rb
gir_ffi-0.13.1 lib/gir_ffi/builders/c_to_ruby_convertor.rb
gir_ffi-0.13.0 lib/gir_ffi/builders/c_to_ruby_convertor.rb