diff options
author | Aaron Patterson <tenderlove@ruby-lang.org> | 2022-09-13 08:26:47 -0700 |
---|---|---|
committer | Hiroshi SHIBATA <hsbt@ruby-lang.org> | 2022-10-07 15:18:50 +0900 |
commit | 755d99e8789b84a7d73d5a30f6b5d582e06f7f45 (patch) | |
tree | 109cd9f14170e5e7240ad680a2d0c80e62f3ac97 /test/fiddle/test_import.rb | |
parent | 48a64984063532f4dedf62e8ac4958a3cf3b556d (diff) |
[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:
```ruby
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:
```ruby
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 <kou@clear-code.com>
Diffstat (limited to 'test/fiddle/test_import.rb')
-rw-r--r-- | test/fiddle/test_import.rb | 6 |
1 files changed, 6 insertions, 0 deletions
diff --git a/test/fiddle/test_import.rb b/test/fiddle/test_import.rb index ca51781e8a..b4dab3de27 100644 --- a/test/fiddle/test_import.rb +++ b/test/fiddle/test_import.rb @@ -139,6 +139,12 @@ module Fiddle end end + def test_type_constants + Fiddle::Types.constants.each do |const| + assert_equal Fiddle::Types.const_get(const), Fiddle.const_get("TYPE_#{const}") + end + end + def test_unsigned_result() d = (2 ** 31) + 1 |