Class: AMQ::BitSet

Inherits:
Object
  • Object
show all
Defined in:
lib/amq/bit_set.rb

Overview

Very minimalistic, pure Ruby implementation of bit set. Inspired by java.util.BitSet, although significantly smaller in scope.

Originally part of amqp gem. Extracted to make it possible for Bunny to use it.

Constant Summary

ADDRESS_BITS_PER_WORD =

API

6
BITS_PER_WORD =
(1 << ADDRESS_BITS_PER_WORD)
WORD_MASK =
0xffffffffffffffff

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (BitSet) initialize(nbits)

Returns a new instance of BitSet



21
22
23
24
25
# File 'lib/amq/bit_set.rb', line 21

def initialize(nbits)
  @nbits = nbits

  self.init_words(nbits)
end

Instance Attribute Details

- (Object) words_in_use (readonly)

Returns the value of attribute words_in_use



10
11
12
# File 'lib/amq/bit_set.rb', line 10

def words_in_use
  @words_in_use
end

Class Method Details

+ (Object) number_of_trailing_ones(num)



93
94
95
96
97
98
# File 'lib/amq/bit_set.rb', line 93

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

Instance Method Details

- (Object) clear

Clears all bits in the set



66
67
68
# File 'lib/amq/bit_set.rb', line 66

def clear
  self.init_words(@nbits)
end

- (Boolean) get(i) Also known as: []

Fetches flag value for given bit.



43
44
45
46
47
48
# File 'lib/amq/bit_set.rb', line 43

def get(i)
  check_range(i)
  w = self.word_index(i)

  (@words[w] & (1 << i % BITS_PER_WORD)) != 0
end

- (Object) next_clear_bit

clear



70
71
72
73
74
75
76
77
78
# File 'lib/amq/bit_set.rb', line 70

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

- (Object) set(i)

Sets (flags) given bit. This method allows bits to be set more than once in a row, no exception will be raised.



31
32
33
34
35
36
# File 'lib/amq/bit_set.rb', line 31

def set(i)
  check_range(i)
  w = self.word_index(i)
  result = @words[w] |= (1 << (i % BITS_PER_WORD))
  result
end

- (Object) to_s

next_clear_bit



80
81
82
83
84
85
86
# File 'lib/amq/bit_set.rb', line 80

def to_s
  result = ""
  @words.each do |w|
    result += w.to_s(2).rjust(BITS_PER_WORD,'0') + ":"
  end
  result
end

- (Object) unset(i)

Unsets (unflags) given bit. This method allows bits to be unset more than once in a row, no exception will be raised.



55
56
57
58
59
60
61
62
# File 'lib/amq/bit_set.rb', line 55

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

- (Object) word_index(i)



101
102
103
# File 'lib/amq/bit_set.rb', line 101

def word_index(i)
  i >> ADDRESS_BITS_PER_WORD
end