Class: PatronusFati::BitField

Inherits:
Object
  • Object
show all
Defined in:
lib/patronus_fati/bit_field.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count) ⇒ BitField

Returns a new instance of BitField.

Raises:

  • (ArgumentError)


19
20
21
22
23
24
# File 'lib/patronus_fati/bit_field.rb', line 19

def initialize(count)
  raise ArgumentError if count <= 0

  self.bits = 0
  self.tracked_count = count
end

Instance Attribute Details

#bitsvoid

Returns the value of attribute bits.



3
4
5
# File 'lib/patronus_fati/bit_field.rb', line 3

def bits
  @bits
end

#tracked_countvoid

Returns the value of attribute tracked_count.



3
4
5
# File 'lib/patronus_fati/bit_field.rb', line 3

def tracked_count
  @tracked_count
end

Instance Method Details

#any_set_in?(rng) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
# File 'lib/patronus_fati/bit_field.rb', line 5

def any_set_in?(rng)
  rng.find { |i| bit_set?(i) }
end

#bit_set?(bit) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


9
10
11
12
# File 'lib/patronus_fati/bit_field.rb', line 9

def bit_set?(bit)
  raise ArgumentError, "Bit #{bit} is out of range of #{tracked_count}" unless valid_bit?(bit)
  (bits & (1 << (bit - 1))) > 0
end

#highest_bit_setvoid



14
15
16
17
# File 'lib/patronus_fati/bit_field.rb', line 14

def highest_bit_set
  return nil if bits == 0
  tracked_count.times.reverse_each.find { |i| bit_set?(i + 1) } + 1
end

#lowest_bit_setvoid



26
27
28
29
# File 'lib/patronus_fati/bit_field.rb', line 26

def lowest_bit_set
  return nil if bits == 0
  tracked_count.times.each.find { |i| bit_set?(i + 1) } + 1
end

#set_bit(bit) ⇒ void

Raises:

  • (ArgumentError)


31
32
33
34
# File 'lib/patronus_fati/bit_field.rb', line 31

def set_bit(bit)
  raise ArgumentError, "Bit #{bit} is out of range of #{tracked_count}" unless valid_bit?(bit)
  self.bits |= (1 << bit - 1)
end

#to_svoid



40
41
42
# File 'lib/patronus_fati/bit_field.rb', line 40

def to_s
  bits.to_s(2).rjust(tracked_count, '0')
end

#valid_bit?(bit) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/patronus_fati/bit_field.rb', line 36

def valid_bit?(bit)
  bit > 0 && bit <= tracked_count
end