Class: ZipTricks::StreamCRC32

Inherits:
Object
  • Object
show all
Defined in:
lib/zip_tricks/stream_crc32.rb

Overview

A simple stateful class for keeping track of a CRC32 value through multiple writes

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStreamCRC32

Creates a new streaming CRC32 calculator



29
30
31
# File 'lib/zip_tricks/stream_crc32.rb', line 29

def initialize
  @crc = Zlib.crc32('')
end

Class Method Details

.from_io(io) ⇒ Fixnum

Compute a CRC32 value from an IO object. The object should respond to read and eof?

Parameters:

  • io (IO)

    the IO to read the data from

Returns:

  • (Fixnum)

    the computed CRC32 value



18
19
20
21
22
23
24
25
26
# File 'lib/zip_tricks/stream_crc32.rb', line 18

def self.from_io(io)
  # If we can specify the string capacity upfront we will not have to resize
  # the string during operation. This saves time but is only available on
  # recent Ruby 2.x versions.
  blob = STRINGS_HAVE_CAPACITY_SUPPORT ? String.new('', capacity: CRC_BUF_SIZE) : String.new('')
  crc = new
  crc << io.read(CRC_BUF_SIZE, blob) until io.eof?
  crc.to_i
end

Instance Method Details

#<<(blob) ⇒ self

Append data to the CRC32. Updates the contained CRC32 value in place.

Parameters:

  • blob (String)

    the string to compute the CRC32 from

Returns:

  • (self)


37
38
39
40
# File 'lib/zip_tricks/stream_crc32.rb', line 37

def <<(blob)
  @crc = Zlib.crc32_combine(@crc, Zlib.crc32(blob), blob.bytesize)
  self
end

#append(crc32, blob_size) ⇒ Fixnum

Appends a known CRC32 value to the current one, and combines the contained CRC32 value in-place.

Parameters:

  • crc32 (Fixnum)

    the CRC32 value to append

  • blob_size (Fixnum)

    the size of the daata the crc32 is computed from

Returns:

  • (Fixnum)

    the updated CRC32 value for all the blobs so far



55
56
57
# File 'lib/zip_tricks/stream_crc32.rb', line 55

def append(crc32, blob_size)
  @crc = Zlib.crc32_combine(@crc, crc32, blob_size)
end

#to_iFixnum

Returns the CRC32 value computed so far

Returns:

  • (Fixnum)

    the updated CRC32 value for all the blobs so far



45
46
47
# File 'lib/zip_tricks/stream_crc32.rb', line 45

def to_i
  @crc
end