Class: PDF::Reader::LZW::BitStream

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf/reader/lzw.rb

Overview

Wraps an LZW encoded string

Instance Method Summary collapse

Constructor Details

#initialize(data, bits_in_chunk) ⇒ BitStream

:nodoc:



25
26
27
28
29
30
31
# File 'lib/pdf/reader/lzw.rb', line 25

def initialize(data, bits_in_chunk)
  @data = data
  @data.force_encoding("BINARY")
  set_bits_in_chunk(bits_in_chunk)
  @current_pos = 0
  @bits_left_in_byte = 8
end

Instance Method Details

#readObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/pdf/reader/lzw.rb', line 39

def read
  bits_left_in_chunk = @bits_in_chunk
  chunk = -1
  while bits_left_in_chunk > 0 and @current_pos < @data.size
    chunk = 0 if chunk < 0
    codepoint = @data[@current_pos, 1].to_s.unpack("C*")[0].to_i
    current_byte = codepoint & (2**@bits_left_in_byte - 1).to_i #clear consumed bits
    dif = bits_left_in_chunk - @bits_left_in_byte
    if dif > 0 then  current_byte <<= dif
    elsif dif < 0 then  current_byte >>= dif.abs
    end
    chunk |= current_byte #add bits to result
    bits_left_in_chunk = if dif >= 0 then dif else 0 end
    @bits_left_in_byte = if dif < 0 then dif.abs else 0 end
    if @bits_left_in_byte.zero? #next byte
      @current_pos += 1
      @bits_left_in_byte = 8
    end
  end
  chunk
end

#set_bits_in_chunk(bits_in_chunk) ⇒ Object

Raises:



33
34
35
36
37
# File 'lib/pdf/reader/lzw.rb', line 33

def set_bits_in_chunk(bits_in_chunk)
  raise MalformedPDFError, "invalid LZW bits" if bits_in_chunk < 9 || bits_in_chunk > 12

  @bits_in_chunk = bits_in_chunk
end