Class: Origami::Filter::Utils::BitReader

Inherits:
Object
  • Object
show all
Defined in:
lib/origami/filters.rb

Overview

Class used to read a String as a stream of bits. Internally used by some filters.

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ BitReader

Returns a new instance of BitReader.



133
134
135
136
# File 'lib/origami/filters.rb', line 133

def initialize(data)
  @data = data
  reset
end

Instance Method Details

#eod?Boolean

Returns true if end of data has been reached.

Returns:



149
150
151
# File 'lib/origami/filters.rb', line 149

def eod?
  @ptr_byte >= @data.size
end

#peek(length) ⇒ Object

Reads length bits as a Fixnum. Does not advance read pointer.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/origami/filters.rb', line 193

def peek(length)
  return BitReaderError, "Invalid read length" unless length > 0 
  return BitReaderError, "Insufficient data" if self.pos + length > self.size

  n = 0
  ptr_byte, ptr_bit = @ptr_byte, @ptr_bit

  while length > 0
    byte = @data[ptr_byte].ord
    
    if length > 8 - ptr_bit
      length -= 8 - ptr_bit
      n |= ( byte & ((1 << (8 - ptr_bit)) - 1) ) << length

      ptr_byte += 1
      ptr_bit = 0
    else
      n |= (byte >> (8 - ptr_bit - length)) & ((1 << length) - 1)
      length = 0
    end
  end

  n
end

#posObject

Returns the read pointer position in bits.



156
157
158
# File 'lib/origami/filters.rb', line 156

def pos
  (@ptr_byte << 3) + @ptr_bit
end

#pos=(bits) ⇒ Object

Sets the read pointer position in bits.

Raises:



170
171
172
173
174
175
176
177
178
# File 'lib/origami/filters.rb', line 170

def pos=(bits)
  raise BitReaderError, "Pointer position out of data" if bits > self.size

  pbyte = bits >> 3
  pbit = bits - (pbyte << 3)
  @ptr_byte, @ptr_bit = pbyte, pbit
  
  bits
end

#read(length) ⇒ Object

Reads length bits as a Fixnum and advances read pointer.



183
184
185
186
187
188
# File 'lib/origami/filters.rb', line 183

def read(length)
  n = self.peek(length)
  self.pos += length

  n
end

#resetObject

Resets the read pointer.



141
142
143
144
# File 'lib/origami/filters.rb', line 141

def reset
  @ptr_byte, @ptr_bit = 0, 0
  self
end

#sizeObject

Returns the data size in bits.



163
164
165
# File 'lib/origami/filters.rb', line 163

def size
  @data.size << 3
end