Class: HexaPDF::Utils::BitStreamReader
- Inherits:
-
Object
- Object
- HexaPDF::Utils::BitStreamReader
- Defined in:
- lib/hexapdf/utils/bit_stream.rb
Overview
Helper class for reading variable length integers from a bit stream.
This class allows one to read integers with a variable width of up to 16 bit 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.
Instance Method Summary collapse
-
#append_data(str) ⇒ Object
Appends some data to the string from where bits are read.
-
#initialize(data = '') ⇒ BitStreamReader
constructor
Creates a new object, optionally providing the string from where the bits should be read.
-
#read(bits) ⇒ Object
Reads
bits
number of bits. -
#read?(bits) ⇒ Boolean
Returns
true
ifbits
number of bits can be read. -
#remaining_bits ⇒ Object
Returns the number of remaining bits that can be read.
Constructor Details
#initialize(data = '') ⇒ BitStreamReader
Creates a new object, optionally providing the string from where the bits should be read.
47 48 49 50 51 52 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 47 def initialize(data = '') @data = data.force_encoding(Encoding::BINARY) @pos = 0 @bit_cache = 0 @available_bits = 0 end |
Instance Method Details
#append_data(str) ⇒ Object
Appends some data to the string from where bits are read.
55 56 57 58 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 55 def append_data(str) @data = @data[@pos, @data.length - @pos] << str @pos = 0 end |
#read(bits) ⇒ Object
Reads bits
number of bits.
Raises an exception if not enough bits are available for reading.
74 75 76 77 78 79 80 81 82 83 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 74 def read(bits) fill_bit_cache raise HexaPDF::Error, "Not enough bits available for reading" if @available_bits < bits @available_bits -= bits result = @bit_cache >> @available_bits @bit_cache &= (1 << @available_bits) - 1 result end |
#read?(bits) ⇒ Boolean
Returns true
if bits
number of bits can be read.
66 67 68 69 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 66 def read?(bits) fill_bit_cache @available_bits >= bits end |
#remaining_bits ⇒ Object
Returns the number of remaining bits that can be read.
61 62 63 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 61 def remaining_bits (@data.length - @pos) * 8 + @available_bits end |