Skip to content

Commit 8eab55b

Browse files
ankanekou
andauthored
Make pointer size consistent between backends (#183)
This PR makes the pointer size consistent between backends. Follow up to #179. ```ruby require "fiddle" ptr = Fiddle::Pointer.new(0) p ptr.size p ptr.ref.size ptr = Fiddle::Pointer["hello world"] ptr.size = 0 p ptr.to_s p ptr.to_str ``` JRuby + TruffleRuby before ```text 9223372036854775807 8 "" "" ``` CRuby + JRuby + TruffleRuby after ```text 0 0 "hello world" "" ``` --------- Co-authored-by: Sutou Kouhei <[email protected]>
1 parent 6ffba40 commit 8eab55b

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/fiddle/ffi_backend.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,13 @@ def initialize(addr, size = nil, free = nil)
323323
FFI::Pointer.new(Integer(addr))
324324
end
325325

326-
@size = size ? size : ptr.size
326+
if size
327+
@size = size
328+
elsif ptr.size_limit?
329+
@size = ptr.size
330+
else
331+
@size = 0
332+
end
327333
@free = free
328334
@ffi_ptr = ptr
329335
@freed = false
@@ -413,6 +419,8 @@ def to_i
413419
def to_s(len = nil)
414420
if len
415421
ffi_ptr.read_string(len)
422+
elsif @size == 0
423+
ffi_ptr.read_string
416424
else
417425
ffi_ptr.get_string(0, @size)
418426
end
@@ -486,6 +494,7 @@ def -@
486494
def ref
487495
cptr = Pointer.malloc(FFI::Type::POINTER.size, RUBY_FREE)
488496
cptr.ffi_ptr.put_pointer(0, ffi_ptr)
497+
cptr.size = 0
489498
cptr
490499
end
491500
end

test/fiddle/test_pointer.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,9 @@ def test_to_str
8181

8282
ptr[5] = 0
8383
assert_equal "hello\0world", ptr.to_str
84+
85+
ptr.size = 0
86+
assert_equal "", ptr.to_str
8487
end
8588

8689
def test_to_s
@@ -93,6 +96,9 @@ def test_to_s
9396
ptr[5] = 0
9497
assert_equal 'hello', ptr.to_s
9598
assert_equal "hello\0", ptr.to_s(6)
99+
100+
ptr.size = 0
101+
assert_equal "hello", ptr.to_s
96102
end
97103

98104
def test_minus
@@ -256,6 +262,8 @@ def test_size
256262
Pointer.malloc(4, Fiddle::RUBY_FREE) do |ptr|
257263
assert_equal 4, ptr.size
258264
end
265+
assert_equal 0, Pointer.new(0).size
266+
assert_equal 0, Pointer.new(0).ref.size
259267
end
260268

261269
def test_size=

0 commit comments

Comments
 (0)