summaryrefslogtreecommitdiff
path: root/spec/ruby/core/io/buffer/bit_count_spec.rb
blob: 62f56f5b985b147f04577c659aabd9b1f9621a4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
require_relative '../../../spec_helper'

ruby_version_is "4.1" do
  describe "IO::Buffer#bit_count" do
    it "counts all set bits in the whole buffer" do
      IO::Buffer.for(+"\xFF\x00\x0F") do |buffer|
        buffer.bit_count.should == 12
      end
    end

    it "returns 0 for a buffer of all zero bytes" do
      IO::Buffer.for(+"\x00\x00\x00") do |buffer|
        buffer.bit_count.should == 0
      end
    end

    it "returns 8 * size for a buffer of all 0xFF bytes" do
      IO::Buffer.for(+"\xFF" * 9) do |buffer|
        buffer.bit_count.should == 72
      end
    end

    it "returns 0 for an empty buffer" do
      IO::Buffer.new(0).bit_count.should == 0
    end

    it "accepts an offset to start counting from (length defaults to remaining bytes)" do
      IO::Buffer.for(+"\xFF\x00\x0F") do |buffer|
        buffer.bit_count(0).should == 12  # offset=0 => entire buffer
        buffer.bit_count(1).should == 4   # offset=1 => 0x00 + 0x0F
        buffer.bit_count(2).should == 4   # offset=2 => 0x0F only
      end
    end

    it "accepts an offset and length to restrict the counted region" do
      IO::Buffer.for(+"\xFF\x00\x0F") do |buffer|
        buffer.bit_count(0, 1).should == 8  # just 0xFF
        buffer.bit_count(1, 1).should == 0  # just 0x00
        buffer.bit_count(2, 1).should == 4  # just 0x0F
        buffer.bit_count(1, 2).should == 4  # 0x00 + 0x0F
      end
    end

    it "handles 8-byte aligned buffers efficiently" do
      IO::Buffer.for(+"\xAA" * 8) do |buffer|
        # 0xAA = 10101010 => 4 bits per byte => 32 total
        buffer.bit_count.should == 32
      end
    end

    it "raises ArgumentError when offset + length exceeds buffer size" do
      IO::Buffer.for(+"\xFF") do |buffer|
        -> { buffer.bit_count(0, 2) }.should.raise(ArgumentError)
        -> { buffer.bit_count(1, 1) }.should.raise(ArgumentError)
      end
    end

    it "returns an Integer" do
      IO::Buffer.for(+"\xFF") do |buffer|
        buffer.bit_count.should.is_a?(Integer)
      end
    end
  end
end