class HexaPDF::Utils::BitStreamReader

Helper class for reading variable length integers from a bit stream.

This class allows one to read integers with a variable width from a bit stream using the read method. The data from where these bits are read, can be set on intialization and additional data can later be appended.

Public Class Methods

new(data = +'') click to toggle source

Creates a new object, optionally providing the string from where the bits should be read.

# File lib/hexapdf/utils/bit_stream.rb, line 49
def initialize(data = +'')
  @data = data.force_encoding(Encoding::BINARY)
  @pos = 0
  @bit_cache = 0
  @available_bits = 0
end

Public Instance Methods

<<(str)
Alias for: append_data
append_data(str) click to toggle source

Appends some data to the string from where bits are read.

# File lib/hexapdf/utils/bit_stream.rb, line 57
def append_data(str)
  @data.slice!(0, @pos)
  @data << str
  @pos = 0
  self
end
Also aliased as: <<
read(bits) click to toggle source

Reads bits number of bits.

Returns nil if not enough bits are available for reading.

# File lib/hexapdf/utils/bit_stream.rb, line 78
def read(bits)
  while @available_bits < bits
    @bit_cache = (@bit_cache << 8) | (@data.getbyte(@pos) || return)
    @pos += 1
    @available_bits += 8
  end
  @available_bits -= bits
  result = (@bit_cache >> @available_bits)
  @bit_cache &= (1 << @available_bits) - 1
  result
end
read?(bits) click to toggle source

Returns true if bits number of bits can be read.

# File lib/hexapdf/utils/bit_stream.rb, line 71
def read?(bits)
  remaining_bits >= bits
end
remaining_bits() click to toggle source

Returns the number of remaining bits that can be read.

# File lib/hexapdf/utils/bit_stream.rb, line 66
def remaining_bits
  (@data.length - @pos) * 8 + @available_bits
end