Class: HexaPDF::Utils::BitStreamWriter
- Inherits:
-
Object
- Object
- HexaPDF::Utils::BitStreamWriter
- 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
-
#finalize ⇒ Object
Retrieves the final (zero padded) bits as a string.
-
#initialize ⇒ BitStreamWriter
constructor
:nodoc:.
-
#write(int, bits) ⇒ Object
Writes the integer
int
with a width ofbits
to the bit stream.
Constructor Details
#initialize ⇒ BitStreamWriter
:nodoc:
103 104 105 106 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 103 def initialize # :nodoc: @bit_cache = 0 @available_bits = 0 end |
Instance Method Details
#finalize ⇒ Object
Retrieves the final (zero padded) bits as a string.
126 127 128 129 130 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 126 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.
112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/hexapdf/utils/bit_stream.rb', line 112 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 |