Project

General

Profile

« Previous | Next » 

Revision 755d99e8

Added by tenderlovemaking (Aaron Patterson) almost 3 years ago

[ruby/fiddle] Move "type" constants to Fiddle::Types (https://github.com/ruby/fiddle/pull/112)

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.

https://github.com/ruby/fiddle/commit/49fa7233e5

Co-authored-by: Sutou Kouhei