Class: Omnizip::Checksums::Crc32

Inherits:
CrcBase
  • Object
show all
Defined in:
lib/omnizip/checksums/crc32.rb

Overview

CRC32 checksum implementation using IEEE 802.3 polynomial.

This implementation uses the standard CRC32 polynomial (0xEDB88320) as used in 7-Zip, ZIP archives, PNG files, and Ethernet frames.

The algorithm uses a 256-entry pre-computed lookup table for efficient O(1) per-byte processing, making it suitable for high-performance checksum calculation.

Polynomial: 0xEDB88320 (reversed IEEE 802.3) Initial value: 0xFFFFFFFF Final XOR: 0xFFFFFFFF Bit width: 32

Examples:

One-shot calculation

checksum = Omnizip::Checksums::Crc32.calculate("abc")
# => 0x352441C2

Incremental calculation

crc = Omnizip::Checksums::Crc32.new
crc.update("Hello, ")
crc.update("world!")
result = crc.finalize

Constant Summary collapse

POLYNOMIAL =

IEEE 802.3 polynomial (reversed representation) This is the standard polynomial used in 7-Zip and ZIP files

0xEDB88320
MASK_32 =

32-bit mask for truncating values

0xFFFFFFFF
TABLE =

Pre-computed lookup table for CRC32 calculation Generated using the IEEE 802.3 polynomial This table is computed once at class load time for performance

generate_table(POLYNOMIAL, 32).freeze

Instance Attribute Summary

Attributes inherited from CrcBase

#value

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CrcBase

calculate, #finalize, generate_table, #initialize, #reset, #update

Constructor Details

This class inherits a constructor from Omnizip::Checksums::CrcBase

Class Method Details

.lookup_tableArray<Integer>

Get the lookup table for CRC32.

Returns:

  • (Array<Integer>)

    256-entry lookup table



93
94
95
# File 'lib/omnizip/checksums/crc32.rb', line 93

def self.lookup_table
  TABLE
end

Instance Method Details

#final_xorInteger

Get the final XOR value for CRC32.

The final result is XORed with all 1s to invert the bits, which is part of the CRC32 standard.

Returns:

  • (Integer)

    0xFFFFFFFF



86
87
88
# File 'lib/omnizip/checksums/crc32.rb', line 86

def final_xor
  MASK_32
end

#initial_valueInteger

Get the initial CRC32 value.

CRC32 starts with all bits set to 1, which helps detect leading zeros in the data stream.

Returns:

  • (Integer)

    0xFFFFFFFF



76
77
78
# File 'lib/omnizip/checksums/crc32.rb', line 76

def initial_value
  MASK_32
end

#process_byte(crc, byte) ⇒ Integer

Process a single byte through the CRC32 algorithm.

Uses the lookup table for efficient computation: new_crc = (old_crc >> 8) ^ table[(old_crc ^ byte) & 0xFF]

Parameters:

  • crc (Integer)

    current CRC value

  • byte (Integer)

    byte to process (0-255)

Returns:

  • (Integer)

    updated CRC value



65
66
67
68
# File 'lib/omnizip/checksums/crc32.rb', line 65

def process_byte(crc, byte)
  index = (crc ^ byte) & 0xFF
  (crc >> 8) ^ TABLE[index]
end