Skip to content

Commit

Permalink
Merge branch 'pr-13'
Browse files Browse the repository at this point in the history
  • Loading branch information
peterc committed Apr 4, 2022
2 parents ab9512e + 7b281a1 commit 0e1bfe6
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
7 changes: 4 additions & 3 deletions lib/bitarray-array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class BitArray
attr_reader :field
include Enumerable

VERSION = "1.2.0"
VERSION = "1.3.0"
ELEMENT_WIDTH = 32

def initialize(size, field = nil)
Expand Down Expand Up @@ -43,8 +43,9 @@ def each_byte
end

# Returns the total number of bits that are set
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
# Use Brian Kernighan's way, see
# https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
def total_set
@field.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
@field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
end
end
7 changes: 4 additions & 3 deletions lib/bitarray.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class BitArray
attr_reader :field
include Enumerable

VERSION = "1.2.0"
VERSION = "1.3.0"

def initialize(size, field = nil, reverse_byte: true)
@size = size
Expand Down Expand Up @@ -47,9 +47,10 @@ def each_byte
end

# Returns the total number of bits that are set
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
# Use Brian Kernighan's way, see
# https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
def total_set
@field.bytes.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
@field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
end

def byte_position(position)
Expand Down
2 changes: 1 addition & 1 deletion test/test_bitarray.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
require "minitest/autorun"
require "bitarray"
require_relative "../lib/bitarray"

class TestBitArray < Minitest::Test
def setup
Expand Down

0 comments on commit 0e1bfe6

Please sign in to comment.