Class: HexaPDF::Utils::BitStreamWriter

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

Overview

Helper class for writing out variable length integers one after another as bit stream.

This class allows one to write integers with a variable width of up to 16 bit to a bit stream using the #write method. Every time when at least 16 bits are available, the #write method returns those 16 bits as string and removes them from the internal cache.

Once all data has been written, the #finalize method must be called to get the last remaining bits (again as a string).

Instance Method Summary collapse

Constructor Details

#initializeBitStreamWriter

:nodoc:



116
117
118
119
# File 'lib/hexapdf/utils/bit_stream.rb', line 116

def initialize # :nodoc:
  @bit_cache = 0
  @available_bits = 0
end

Instance Method Details

#finalizeObject

Retrieves the final (zero padded) bits as a string.



139
140
141
142
143
# File 'lib/hexapdf/utils/bit_stream.rb', line 139

def finalize
  result = [@bit_cache].pack('N')[0...(@available_bits / 8.0).ceil]
  initialize
  result
end

#write(int, bits) ⇒ Object

Writes the integer int with a width of bits to the bit stream.

Returns a 16bit binary string if enough bits are available or an empty binary string otherwise.



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/hexapdf/utils/bit_stream.rb', line 125

def write(int, bits)
  @available_bits += bits
  @bit_cache |= int << (32 - @available_bits)
  if @available_bits >= 16
    @available_bits -= 16
    result = (@bit_cache >> 24).chr << ((@bit_cache >> 16) & 0xFF).chr
    @bit_cache = (@bit_cache & 0xFFFF) << 16
    result
  else
    ''.b
  end
end