Class: Origami::Filter::Utils::BitWriter

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeBitWriter

Returns a new instance of BitWriter.



53
54
55
56
57
# File 'lib/origami/filters.rb', line 53

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

Instance Method Details

#finalObject

Finalizes the stream.



109
110
111
112
113
114
115
# File 'lib/origami/filters.rb', line 109

def final
  @data << @last_byte.chr if @last_byte
  @last_byte = nil
  @p = 0

  self
end

#sizeObject

Returns the data size in bits.



102
103
104
# File 'lib/origami/filters.rb', line 102

def size
  (@data.size << 3) + @ptr_bit
end

#to_sObject

Outputs the stream as a String.



120
121
122
# File 'lib/origami/filters.rb', line 120

def to_s
  @data.dup
end

#write(data, length) ⇒ Object

Writes data represented as Fixnum to a length number of bits.



62
63
64
65
66
67
68
69
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
# File 'lib/origami/filters.rb', line 62

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 unless @last_byte
      @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 unless @last_byte
      @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