Class: Digest::CRC

Inherits:
Class
  • Object
show all
Includes:
Instance
Defined in:
lib/digest/crc.rb

Overview

Base class for all CRC algorithms.

Direct Known Subclasses

CRC1, CRC15, CRC16, CRC24, CRC32, CRC5, CRC64, CRC8

Constant Summary collapse

INIT_CRC =

The initial value of the CRC checksum

0x00
XOR_MASK =

The XOR mask to apply to the resulting CRC checksum

0x00
WIDTH =

The bit width of the CRC checksum

0
TABLE =

Default place holder CRC table

[].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCRC

Initializes the CRC checksum.



57
58
59
60
61
62
63
64
# File 'lib/digest/crc.rb', line 57

def initialize
  @init_crc = self.class.const_get(:INIT_CRC)
  @xor_mask = self.class.const_get(:XOR_MASK)
  @width    = self.class.const_get(:WIDTH)
  @table    = self.class.const_get(:TABLE)

  reset
end

Class Method Details

.checksum(data) ⇒ Integer

Calculates the CRC checksum.

Parameters:

  • data (String)

    The given data.

Returns:

  • (Integer)

    The CRC checksum.



32
33
34
35
36
37
# File 'lib/digest/crc.rb', line 32

def self.checksum(data)
  crc = self.new
  crc << data

  return crc.checksum
end

.pack(crc) ⇒ String

This method is abstract.

Packs the given CRC checksum.

Parameters:

  • crc (Integer)

    The raw CRC checksum.

Returns:

  • (String)

    The packed CRC checksum.

Raises:

  • (NotImplementedError)


50
51
52
# File 'lib/digest/crc.rb', line 50

def self.pack(crc)
  raise(NotImplementedError,"#{self.class}##{__method__} not implemented")
end

Instance Method Details

#<<(data) ⇒ Object

See Also:



100
101
102
103
# File 'lib/digest/crc.rb', line 100

def <<(data)
  update(data)
  return self
end

#block_length1

The input block length.

Returns:

  • (1)


71
72
73
# File 'lib/digest/crc.rb', line 71

def block_length
  1
end

#checksumInteger

The resulting CRC checksum.

Returns:

  • (Integer)

    The resulting CRC checksum.



121
122
123
# File 'lib/digest/crc.rb', line 121

def checksum
  @crc ^ @xor_mask
end

#digest_lengthInteger

The length of the digest.

Returns:

  • (Integer)

    The length in bytes.



81
82
83
# File 'lib/digest/crc.rb', line 81

def digest_length
  (@width / 8.0).ceil
end

#finishObject

Finishes the CRC checksum calculation.

See Also:



130
131
132
# File 'lib/digest/crc.rb', line 130

def finish
  self.class.pack(checksum)
end

#resetInteger

Resets the CRC checksum.

Returns:

  • (Integer)

    The default value of the CRC checksum.



111
112
113
# File 'lib/digest/crc.rb', line 111

def reset
  @crc = @init_crc
end

#update(data) ⇒ Object

This method is abstract.

Updates the CRC checksum with the given data.

Parameters:

  • data (String)

    The data to update the CRC checksum with.

Raises:

  • (NotImplementedError)


93
94
95
# File 'lib/digest/crc.rb', line 93

def update(data)
  raise(NotImplementedError,"#{self.class}##{__method__} not implemented")
end