ruby / fiddle

A libffi wrapper for Ruby.
BSD 2-Clause "Simplified" License
154 stars 37 forks source link

Move "type" constants to `Fiddle::Types` #112

Closed tenderlove closed 1 year ago

tenderlove commented 2 years ago

This helps to reduce repetition in code. Instead of doing "TYPE_*" everywhere, you can do include Fiddle::Types, and write the type name directly.

This PR is to help reduce repetition when writing Fiddle code. Right now we have to type TYPE_ everywhere, and you also have to include all of Fiddle to access TYPE_* constants. With this change, you can just include Fiddle::Types and it will shorten your code and also you only have to include those constants.

Here is an example before:

require "fiddle"

module MMAP
  # All Fiddle constants included
  include Fiddle

  def self.make_function name, args, ret
    ptr = Handle::DEFAULT[name]
    func = Function.new ptr, args, ret, name: name
    define_singleton_method name, &func.to_proc
  end

  make_function "munmap", [TYPE_VOIDP, # addr
                           TYPE_SIZE_T], # len
                           TYPE_INT

  make_function "mmap", [TYPE_VOIDP,
                         TYPE_SIZE_T,
                         TYPE_INT,
                         TYPE_INT,
                         TYPE_INT,
                         TYPE_INT], TYPE_VOIDP

  make_function "mprotect", [TYPE_VOIDP, TYPE_SIZE_T, TYPE_INT], TYPE_INT
end

After:

require "fiddle"

module MMAP
  # Only type names included
  include Fiddle::Types

  def self.make_function name, args, ret
    ptr = Fiddle::Handle::DEFAULT[name]
    func = Fiddle::Function.new ptr, args, ret, name: name
    define_singleton_method name, &func.to_proc
  end

  make_function "munmap", [VOIDP, # addr
                           SIZE_T], # len
                           INT

  make_function "mmap", [VOIDP, SIZE_T, INT, INT, INT, INT], VOIDP

  make_function "mprotect", [VOIDP, SIZE_T, INT], INT
end

We only need to import the type names, and you don't have to type TYPE_ over and over. I think this makes Fiddle code easier to read.