Class: Bitcoin::BitStreamWriter

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

Constant Summary collapse

MAX_BIT =

2**64

4611686018427387904

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBitStreamWriter

Returns a new instance of BitStreamWriter.



11
12
13
14
15
# File 'lib/bitcoin/bit_stream.rb', line 11

def initialize
  @stream = ''
  @buffer = 0
  @offset = 0
end

Instance Attribute Details

#bufferObject

Returns the value of attribute buffer.



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

def buffer
  @buffer
end

#offsetObject

Returns the value of attribute offset.



9
10
11
# File 'lib/bitcoin/bit_stream.rb', line 9

def offset
  @offset
end

#streamObject (readonly)

Returns the value of attribute stream.



7
8
9
# File 'lib/bitcoin/bit_stream.rb', line 7

def stream
  @stream
end

Instance Method Details

#flushObject



29
30
31
32
33
34
# File 'lib/bitcoin/bit_stream.rb', line 29

def flush
  return if offset == 0
  self.stream << buffer.itb
  self.offset = 0
  self.buffer = 0
end

#write(data, nbits) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/bitcoin/bit_stream.rb', line 17

def write(data, nbits)
  raise "nbits must be between 0 and 64" if nbits < 0 || nbits > 64
  while nbits > 0
    bits = [8 - offset, nbits].min
    tmp = (data << (64 - nbits)) & 0b1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111
    self.buffer |= (tmp >> (64 - 8 + offset))
    self.offset += bits
    nbits -= bits
    flush if offset == 8
  end
end