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 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
(also: #<<)
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.
50 51 52 53 54 55 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 50 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 Also known as: <<
Appends some data to the string from where bits are read.
58 59 60 61 62 63 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 58 def append_data(str) @data.slice!(0, @pos) @data << str @pos = 0 self end |
#read(bits) ⇒ Object
Reads bits
number of bits.
Returns nil
if not enough bits are available for reading.
79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 79 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) ⇒ Boolean
Returns true
if bits
number of bits can be read.
72 73 74 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 72 def read?(bits) remaining_bits >= bits end |
#remaining_bits ⇒ Object
Returns the number of remaining bits that can be read.
67 68 69 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 67 def remaining_bits (@data.length - @pos) * 8 + @available_bits end |