|
| 1 | +require_relative '../../../spec_helper' |
| 2 | + |
| 3 | +ruby_version_is "4.1" do |
| 4 | + describe "IO::Buffer#bit_count" do |
| 5 | + it "counts all set bits in the whole buffer" do |
| 6 | + IO::Buffer.for(+"\xFF\x00\x0F") do |buffer| |
| 7 | + buffer.bit_count.should == 12 |
| 8 | + end |
| 9 | + end |
| 10 | + |
| 11 | + it "returns 0 for a buffer of all zero bytes" do |
| 12 | + IO::Buffer.for(+"\x00\x00\x00") do |buffer| |
| 13 | + buffer.bit_count.should == 0 |
| 14 | + end |
| 15 | + end |
| 16 | + |
| 17 | + it "returns 8 * size for a buffer of all 0xFF bytes" do |
| 18 | + IO::Buffer.for(+"\xFF" * 9) do |buffer| |
| 19 | + buffer.bit_count.should == 72 |
| 20 | + end |
| 21 | + end |
| 22 | + |
| 23 | + it "returns 0 for an empty buffer" do |
| 24 | + IO::Buffer.new(0).bit_count.should == 0 |
| 25 | + end |
| 26 | + |
| 27 | + it "accepts an offset to start counting from (length defaults to remaining bytes)" do |
| 28 | + IO::Buffer.for(+"\xFF\x00\x0F") do |buffer| |
| 29 | + buffer.bit_count(0).should == 12 # offset=0 => entire buffer |
| 30 | + buffer.bit_count(1).should == 4 # offset=1 => 0x00 + 0x0F |
| 31 | + buffer.bit_count(2).should == 4 # offset=2 => 0x0F only |
| 32 | + end |
| 33 | + end |
| 34 | + |
| 35 | + it "accepts an offset and length to restrict the counted region" do |
| 36 | + IO::Buffer.for(+"\xFF\x00\x0F") do |buffer| |
| 37 | + buffer.bit_count(0, 1).should == 8 # just 0xFF |
| 38 | + buffer.bit_count(1, 1).should == 0 # just 0x00 |
| 39 | + buffer.bit_count(2, 1).should == 4 # just 0x0F |
| 40 | + buffer.bit_count(1, 2).should == 4 # 0x00 + 0x0F |
| 41 | + end |
| 42 | + end |
| 43 | + |
| 44 | + it "handles 8-byte aligned buffers efficiently" do |
| 45 | + IO::Buffer.for(+"\xAA" * 8) do |buffer| |
| 46 | + # 0xAA = 10101010 => 4 bits per byte => 32 total |
| 47 | + buffer.bit_count.should == 32 |
| 48 | + end |
| 49 | + end |
| 50 | + |
| 51 | + it "raises ArgumentError when offset + length exceeds buffer size" do |
| 52 | + IO::Buffer.for(+"\xFF") do |buffer| |
| 53 | + -> { buffer.bit_count(0, 2) }.should raise_error(ArgumentError) |
| 54 | + -> { buffer.bit_count(1, 1) }.should raise_error(ArgumentError) |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + it "returns an Integer" do |
| 59 | + IO::Buffer.for(+"\xFF") do |buffer| |
| 60 | + buffer.bit_count.should be_kind_of(Integer) |
| 61 | + end |
| 62 | + end |
| 63 | + end |
| 64 | +end |
0 commit comments