Class: TCD::Writer::BitPacker
- Inherits:
-
Object
- Object
- TCD::Writer::BitPacker
- Defined in:
- lib/tcd/writer.rb
Overview
Bit-level output, most significant bit first, padded with zero bits to a whole byte: the mirror of BitBuffer.
Instance Method Summary collapse
- #bit_length ⇒ Object
- #bytes ⇒ Object
-
#initialize ⇒ BitPacker
constructor
A new instance of BitPacker.
- #write_int(value, bits, what) ⇒ Object
- #write_string(bytes) ⇒ Object
- #write_uint(value, bits, what) ⇒ Object
Constructor Details
#initialize ⇒ BitPacker
Returns a new instance of BitPacker.
829 830 831 832 833 834 |
# File 'lib/tcd/writer.rb', line 829 def initialize @out = String.new(encoding: Encoding::BINARY) @acc = 0 @nbits = 0 @total = 0 end |
Instance Method Details
#bit_length ⇒ Object
836 837 838 |
# File 'lib/tcd/writer.rb', line 836 def bit_length @total end |
#bytes ⇒ Object
862 863 864 865 866 |
# File 'lib/tcd/writer.rb', line 862 def bytes out = @out.dup out << ((@acc << (8 - @nbits)) & 0xFF).chr if @nbits.positive? out end |
#write_int(value, bits, what) ⇒ Object
848 849 850 851 852 853 854 855 |
# File 'lib/tcd/writer.rb', line 848 def write_int(value, bits, what) value = Integer(value) half = 1 << (bits - 1) unless value >= -half && value < half raise RangeError, "#{what} value #{value} does not fit #{bits} signed bits" end put(value & ((1 << bits) - 1), bits) end |
#write_string(bytes) ⇒ Object
857 858 859 860 |
# File 'lib/tcd/writer.rb', line 857 def write_string(bytes) bytes.each_byte { |b| put(b, 8) } put(0, 8) end |
#write_uint(value, bits, what) ⇒ Object
840 841 842 843 844 845 846 |
# File 'lib/tcd/writer.rb', line 840 def write_uint(value, bits, what) value = Integer(value) if value.negative? || value >= (1 << bits) raise RangeError, "#{what} value #{value} does not fit #{bits} unsigned bits" end put(value, bits) end |