Class: Barray::BitArray

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ BitArray

Returns a new instance of BitArray.



10
11
12
13
14
# File 'lib/barray.rb', line 10

def initialize(size)
  @size = size
  @byte_size = (size / 8.0).ceil
  @data = init_data
end

Instance Attribute Details

#sizeObject

Returns the value of attribute size.



8
9
10
# File 'lib/barray.rb', line 8

def size
  @size
end

Instance Method Details

#dumpObject



16
17
18
# File 'lib/barray.rb', line 16

def dump
  data.dup
end

#each_bitObject



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

def each_bit
  return enum_for(:each_bit) unless block_given?

  size.times do |bit_position|
    yield get(bit_position)
  end
end

#get(position) ⇒ Object



41
42
43
44
# File 'lib/barray.rb', line 41

def get(position)
  ensure_position!(position)
  data.getbyte(position / 8) & (1 << (position % 8)) != 0 ? 1 : 0
end

#load(data_in) ⇒ Object



20
21
22
23
24
# File 'lib/barray.rb', line 20

def load(data_in)
  raise LossyOperationError, 'Data size exceeds array size' if data_in.bytesize > byte_size

  self.data = data_in.dup << "\u0000" * (byte_size - data_in.bytesize)
end

#resetObject



46
47
48
# File 'lib/barray.rb', line 46

def reset
  init_data
end

#set(position) ⇒ Object



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

def set(position)
  ensure_position!(position)
  data.setbyte(position / 8, (data.getbyte(position / 8) | (1 << (position % 8))))
end

#set?(position) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
# File 'lib/barray.rb', line 36

def set?(position)
  ensure_position!(position)
  get(position) != 0
end

#set_sizeObject



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/barray.rb', line 63

def set_size
  count = 0

  data.each_byte do |byte|
    next if byte.zero?

    count += byte.to_s(2).split('').reject { |bit| bit == '0' }.length
  end

  count
end

#toggle(position) ⇒ Object



50
51
52
53
# File 'lib/barray.rb', line 50

def toggle(position)
  ensure_position!(position)
  data.setbyte(position / 8, (data.getbyte(position / 8) ^ (1 << (position % 8))))
end

#unset(position) ⇒ Object



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

def unset(position)
  ensure_position!(position)
  data.setbyte(position / 8, (data.getbyte(position / 8) & (255 ^ (1 << (position % 8)))))
end

#unset_sizeObject



75
76
77
# File 'lib/barray.rb', line 75

def unset_size
  size - set_size
end