Repository navigation
Fix Numo::Bit#to_binary returning uninitialized memory in its last byte - #48
Conversation
When the size of a Bit array is not a multiple of 8, the last byte that to_binary returns also holds the bits past the end. For a new array they are uninitialized heap memory. For a view read in place they are elements of the base. They also reach marshal_dump and to_string. Clear those bits in the returned string. Count them on the same array that the byte length came from. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4f0fa0b to
a9e02ad
Compare
|
/opencode review |
Review of PR #48: Fix
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks for the review. I added a test for a Bit subclass that owns its buffer (f542394). Before the fix, About the other suggestions:
|
Purpose
When the size of a
Numo::Bitarray is not a multiple of 8, the last byte thatto_binaryreturns also holds the bits past the end of the array. The buffer is allocated withxmalloc, so these bits are uninitialized heap memory. For a view that is read in place, they are the elements of the base array outside the view.marshal_dumpandto_stringuse the same method, so these bits also reachMarshal.dump. Arrays with the same contents give different bytes, which breaks caches and comparisons keyed on the dump.Summary of Changes
nary_to_binarynow clears the bits past the end in the last byte of the returned string. It counts them on the same array that the byte length came from.An array made by
from_binaryalso kept the extra bits of its input, soNumo::Bit.from_binary("\xFF\xFF".b, [12]).to_binarynow returns"\xFF\x0F"instead of"\xFF\xFF".Cumo fixed the same in sonots/cumo#471.
Testing
Before the fix, 30 calls of
to_binaryon a 1-bit array gave 27 different bytes. After the fix, they all give[1].Marshal.dumpandto_stringof a 5-bit array also give the same bytes on every call.The new test fails on the code before the fix.
test_narray,test_bit,test_extra,test_mathandtest_ractorall pass on Ruby 4.0.10.Related Issues
Relates to sonots/cumo#471.
🤖 Generated with Claude Code