class Origami::Filter::Utils::BitWriter


Internally used by some filters.
Class used to forge a String from a stream of bits.

def final


Finalizes the stream.
def final
    @data << @last_byte.chr if @last_byte
    @last_byte = nil
    @p = 0
    self
end

def initialize

def initialize
    @data = ''.b
    @last_byte = nil
    @ptr_bit = 0
end

def size


Returns the data size in bits.
def size
    (@data.size << 3) + @ptr_bit
end

def to_s


Outputs the stream as a String.
def to_s
    @data.dup
end

def write(data, length)


Writes _data_ represented as Fixnum to a _length_ number of bits.
def write(data, length)
    return BitWriterError, "Invalid data length" unless length > 0 and length >= data.bit_length
    # optimization for aligned byte writing
    if length == 8 and @last_byte.nil? and @ptr_bit == 0
        @data << data.chr
        return self
    end
    write_bits(data, length)
    self
end

def write_bits(data, length)


Write the bits into the internal data.
def write_bits(data, length)
    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
end