summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Kanis <lars@greiz-reinsdorf.de>2020-09-23 20:38:24 +0200
committerLars Kanis <lars@greiz-reinsdorf.de>2020-09-23 20:42:11 +0200
commitf5d68c86765055ad8f1e2c47c5b18bd3bc58d716 (patch)
tree969b03cc430d50aadb1bece9449f731a44aa9546
parent694e97568a0d3bb8f697f5e91ac5464bde707934 (diff)
downloadffi-f5d68c86765055ad8f1e2c47c5b18bd3bc58d716.tar.gz
Always write a final null termination in write_string
When len is given the null character is appended after the truncated string. Due to discussion in https://github.com/ffi/ffi/pull/806#pullrequestreview-451056095 Also add some Unicode characters to point out we're counting bytes, not characters.
-rw-r--r--lib/ffi/pointer.rb8
-rw-r--r--spec/ffi/string_spec.rb18
2 files changed, 13 insertions, 13 deletions
diff --git a/lib/ffi/pointer.rb b/lib/ffi/pointer.rb
index ec6b1b1..778f2b5 100644
--- a/lib/ffi/pointer.rb
+++ b/lib/ffi/pointer.rb
@@ -96,14 +96,14 @@ module FFI
# @param [String] str string to write
# @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+. A final \0 byte is written if +len+ is not given.
+ # Write +str+ in pointer's contents.
+ # If +len+ is given, write the first +len+ bytes of +str+
+ # and append a final \0 byte after the string.
def write_string(str, len=nil)
if len
- # No NUL termination
put_bytes(0, str, 0, len)
+ put_bytes(len, "\0")
else
- # With NUL termination
put_string(0, str)
end
end unless method_defined?(:write_string)
diff --git a/spec/ffi/string_spec.rb b/spec/ffi/string_spec.rb
index 53739a1..dea4e93 100644
--- a/spec/ffi/string_spec.rb
+++ b/spec/ffi/string_spec.rb
@@ -102,16 +102,16 @@ describe "String tests" do
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\x00")
- expect(ptr.read_string).to eq("abc")
+ ptr.write_string("äbc")
+ expect(ptr.read_bytes(5)).to eq("äbc\x00".b)
+ expect(ptr.read_string).to eq("äbc".b)
end
- it "does not write a final \\0 when given a length" do
+ it "writes a final \\0 when given a length" do
ptr = FFI::MemoryPointer.new(8)
ptr.write_int64(-1)
- ptr.write_string("abc", 3)
- expect(ptr.read_bytes(4)).to eq("abc\xFF".b)
+ ptr.write_string("äbcd", 3)
+ expect(ptr.read_bytes(5)).to eq("äb\x00\xFF".b)
end
end
@@ -119,9 +119,9 @@ describe "String tests" do
it "writes a final \\0" do
ptr = FFI::MemoryPointer.new(8)
ptr.write_int64(-1)
- ptr.put_string(0, "abc")
- expect(ptr.read_bytes(4)).to eq("abc\x00")
- expect(ptr.read_string).to eq("abc")
+ ptr.put_string(0, "äbc")
+ expect(ptr.read_bytes(5)).to eq("äbc\x00".b)
+ expect(ptr.read_string).to eq("äbc".b)
end
end
end