Class: Origami::Filter::Utils::BitWriter
- Inherits:
-
Object
- Object
- Origami::Filter::Utils::BitWriter
- Defined in:
- lib/origami/filters.rb
Overview
Class used to forge a String from a stream of bits. Internally used by some filters.
Instance Method Summary collapse
-
#final ⇒ Object
Finalizes the stream.
-
#initialize ⇒ BitWriter
constructor
A new instance of BitWriter.
-
#size ⇒ Object
Returns the data size in bits.
-
#to_s ⇒ Object
Outputs the stream as a String.
-
#write(data, length) ⇒ Object
Writes data represented as Fixnum to a length number of bits.
Constructor Details
#initialize ⇒ BitWriter
Returns a new instance of BitWriter.
61 62 63 64 65 |
# File 'lib/origami/filters.rb', line 61 def initialize @data = '' @last_byte = nil @ptr_bit = 0 end |
Instance Method Details
#final ⇒ Object
Finalizes the stream.
117 118 119 120 121 122 123 |
# File 'lib/origami/filters.rb', line 117 def final @data << @last_byte.chr if @last_byte @last_byte = nil @p = 0 self end |
#size ⇒ Object
Returns the data size in bits.
110 111 112 |
# File 'lib/origami/filters.rb', line 110 def size (@data.size << 3) + @ptr_bit end |
#to_s ⇒ Object
Outputs the stream as a String.
128 129 130 |
# File 'lib/origami/filters.rb', line 128 def to_s @data.dup end |
#write(data, length) ⇒ Object
Writes data represented as Fixnum to a length number of bits.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/origami/filters.rb', line 70 def write(data, length) return BitWriterError, "Invalid data length" unless length > 0 and (1 << length) > data # optimization for aligned byte writing if length == 8 and @last_byte.nil? and @ptr_bit == 0 @data << data.chr return self end while length > 0 if length >= 8 - @ptr_bit length -= 8 - @ptr_bit @last_byte ||= 0 @last_byte |= (data >> length) & ((1 << (8 - @ptr_bit)) - 1) data &= (1 << length) - 1 @data << @last_byte.chr @last_byte = nil @ptr_bit = 0 else @last_byte ||= 0 @last_byte |= (data & ((1 << length) - 1)) << (8 - @ptr_bit - length) @ptr_bit += length if @ptr_bit == 8 @data << @last_byte.chr @last_byte = nil @ptr_bit = 0 end length = 0 end end self end |