summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBenoit Daloze <eregontp@gmail.com>2020-07-11 15:33:53 +0200
committerBenoit Daloze <eregontp@gmail.com>2020-07-11 15:46:23 +0200
commit8fd92407a267c917669c349e06485ec336e95bac (patch)
tree7f4651155c15fdfb2854d8d85b9af1c418756b95
parentddd36ae1c60a9bcacbfad6ebd98ee766e61e429e (diff)
downloadffi-8fd92407a267c917669c349e06485ec336e95bac.tar.gz
Fix FFI::Pointer#write_string to terminate with a NUL byte if not given a length
* Fixes #805
-rw-r--r--lib/ffi/pointer.rb12
-rw-r--r--spec/ffi/string_spec.rb6
2 files changed, 12 insertions, 6 deletions
diff --git a/lib/ffi/pointer.rb b/lib/ffi/pointer.rb
index a5ee655..ec6b1b1 100644
--- a/lib/ffi/pointer.rb
+++ b/lib/ffi/pointer.rb
@@ -97,11 +97,15 @@ module FFI
# @param [Numeric] len length of string to return
# @return [self]
# Write +str+ in pointer's contents, or first +len+ bytes if
- # +len+ is not +nil+.
+ # +len+ is not +nil+. A final \0 byte is written if +len+ is not given.
def write_string(str, len=nil)
- len = str.bytesize unless len
- # Write the string data without NUL termination
- put_bytes(0, str, 0, len)
+ if len
+ # No NUL termination
+ put_bytes(0, str, 0, len)
+ else
+ # With NUL termination
+ put_string(0, str)
+ end
end unless method_defined?(:write_string)
# @param [Type] type type of data to read from pointer's contents
diff --git a/spec/ffi/string_spec.rb b/spec/ffi/string_spec.rb
index 6b080e4..53739a1 100644
--- a/spec/ffi/string_spec.rb
+++ b/spec/ffi/string_spec.rb
@@ -98,11 +98,13 @@ describe "String tests" do
end
describe "#write_string" do
- it "does not write a final \\0 when given no length" do
+ # https://github.com/ffi/ffi/issues/805
+ it "writes a final \\0 when given no length" do
ptr = FFI::MemoryPointer.new(8)
ptr.write_int64(-1)
ptr.write_string("abc")
- expect(ptr.read_bytes(4)).to eq("abc\xFF".b)
+ expect(ptr.read_bytes(4)).to eq("abc\x00")
+ expect(ptr.read_string).to eq("abc")
end
it "does not write a final \\0 when given a length" do