class AMQ::BitSet
Originally part of amqp gem. Extracted to make it possible for Bunny to use it.
although significantly smaller in scope.
Very minimalistic, pure Ruby implementation of bit set. Inspired by java.util.BitSet,
def self.number_of_trailing_ones(num)
- Private: -
def self.number_of_trailing_ones(num) 0.upto(BITS_PER_WORD) do |bit| return bit if num[bit] == 0 end BITS_PER_WORD end # number_of_trailing_ones
def check_range(i)
def check_range(i) if i < 0 || i >= @nbits raise IndexError.new("Cannot access bit #{i} from a BitSet with #{@nbits} bits") end end # check_range
def clear
- Api: - public
def clear self.init_words(@nbits) end # clear
def get(i)
- Api: - public
Returns:
-
(Boolean)- true if given bit is set, false otherwise
Parameters:
-
A(Integer) -- bit to fetch
def get(i) check_range(i) w = self.word_index(i) (@words[w] & (1 << i % BITS_PER_WORD)) != 0 end # get(i)
def init_words(nbits)
- Private: -
def init_words(nbits) n = word_index(nbits-1) + 1 @words = Array.new(n) { 0 } end # init_words
def initialize(nbits)
- Api: - public
Parameters:
-
Number(Integer) -- of bits in the set
def initialize(nbits) @nbits = nbits self.init_words(nbits) end # initialize(nbits)
def next_clear_bit()
def next_clear_bit() @words.each_with_index do |word, i| if word == WORD_MASK next end return i * BITS_PER_WORD + BitSet.number_of_trailing_ones(word) end -1 end # next_clear_bit
def set(i)
- Api: - public
Parameters:
-
A(Integer) -- bit to set
def set(i) check_range(i) w = self.word_index(i) result = @words[w] |= (1 << (i % BITS_PER_WORD)) result end # set(i)
def to_s
def to_s result = "" @words.each do |w| result += w.to_s(2).rjust(BITS_PER_WORD,'0') + ":" end result end # to_s
def unset(i)
- Api: - public
Parameters:
-
A(Integer) -- bit to unset
def unset(i) check_range(i) w = self.word_index(i) return if w.nil? result = @words[w] &= ~(1 << i % BITS_PER_WORD) result end # unset(i)
def word_index(i)
- Private: -
def word_index(i) i >> ADDRESS_BITS_PER_WORD end # word_index