Class: ZPNG::Chunk

Inherits:
Object
  • Object
show all
Defined in:
lib/zpng/chunk.rb

Direct Known Subclasses

IEND, IHDR, PLTE

Defined Under Namespace

Classes: IEND, IHDR, PLTE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ Chunk

Returns a new instance of Chunk.



21
22
23
24
25
# File 'lib/zpng/chunk.rb', line 21

def initialize io
  @size, @type = io.read(8).unpack('Na4')
  @data        = io.read(size)
  @crc         = io.read(4).to_s.unpack('N').first
end

Instance Attribute Details

#crcObject

Returns the value of attribute crc.



3
4
5
# File 'lib/zpng/chunk.rb', line 3

def crc
  @crc
end

#dataObject

Returns the value of attribute data.



3
4
5
# File 'lib/zpng/chunk.rb', line 3

def data
  @data
end

#sizeObject

Returns the value of attribute size.



3
4
5
# File 'lib/zpng/chunk.rb', line 3

def size
  @size
end

#typeObject

Returns the value of attribute type.



3
4
5
# File 'lib/zpng/chunk.rb', line 3

def type
  @type
end

Class Method Details

.from_stream(io) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/zpng/chunk.rb', line 5

def self.from_stream io
  size, type = io.read(8).unpack('Na4')
  io.seek(-8,IO::SEEK_CUR)
  begin
    if const_defined?(type.upcase)
      klass = const_get(type.upcase)
      klass.new(io)
    else
      Chunk.new(io)
    end
  rescue NameError
    # invalid chunk type?
    Chunk.new(io)
  end
end

Instance Method Details

#crc_ok?Boolean

Returns:

  • (Boolean)


45
46
47
48
# File 'lib/zpng/chunk.rb', line 45

def crc_ok?
  expected_crc = Zlib.crc32(data, Zlib.crc32(type))
  expected_crc == crc
end

#exportObject



27
28
29
30
31
# File 'lib/zpng/chunk.rb', line 27

def export
  @data = self.export_data # virtual
  @crc = Zlib.crc32(data, Zlib.crc32(type))
  [@size,@type].pack('Na4') + @data + [@crc].pack('N')
end

#export_dataObject



33
34
35
36
# File 'lib/zpng/chunk.rb', line 33

def export_data
  #STDERR.puts "[!] Chunk::#{type} must realize 'export_data' virtual method".yellow if @size != 0
  @data
end

#inspectObject



38
39
40
41
42
43
# File 'lib/zpng/chunk.rb', line 38

def inspect
  size = @size ? sprintf("%5d",@size) : sprintf("%5s","???")
  crc  = @crc  ? sprintf("%08x",@crc) : sprintf("%8s","???")
  type = @type.to_s.gsub(/[^0-9a-z]/i){ |x| sprintf("\\x%02X",x.ord) }
  sprintf("#<ZPNG::Chunk  %4s size=%s, crc=%s >", type, size, crc)
end