Class: Junkfood::Adler32

Inherits:
Object
  • Object
show all
Defined in:
lib/junkfood/adler32.rb

Overview

A Ruby implementation of the Adler-32 checksum algorithm, which uses Ruby’s own Zlib.adler32 class method.

This Ruby implementation is a port of the Python adler32 implementation found in the pysync project. The Python reference implementation, itself, was a port from zlib’s adler32.c file.

Constant Summary collapse

BASE =

largest prime smaller than 65536

65521
NMAX =

largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1

5552
OFFS =

default initial s1 offset

1

Instance Method Summary collapse

Constructor Details

#initialize(data = '') ⇒ Adler32

Returns a new instance of Adler32.

Parameters:

  • data (String) (defaults to: '')

    initial block of data to digest.



43
44
45
46
47
# File 'lib/junkfood/adler32.rb', line 43

def initialize(data='')
  value = Zlib.adler32(data, OFFS)
  @s2, @s1 = (value >> 16) & 0xffff, value & 0xffff
  @count = data.length
end

Instance Method Details

#digestFixnum

Returns the current Adler32 digest value.

Returns:

  • (Fixnum)

    the current Adler32 digest value.



98
99
100
# File 'lib/junkfood/adler32.rb', line 98

def digest
  return (@s2 << 16) | @s1
end

#rollin(b) ⇒ Fixnum

Returns the updated digest.

Parameters:

  • b (Byte)

Returns:

  • (Fixnum)

    the updated digest.



77
78
79
80
81
82
# File 'lib/junkfood/adler32.rb', line 77

def rollin(b)
  @s1 = (@s1 + b) % BASE
  @s2 = (@s2 + @s1) % BASE
  @count = @count + 1
  return self.digest
end

#rollout(b) ⇒ Fixnum

Returns the updated digest.

Parameters:

  • b (Byte)

Returns:

  • (Fixnum)

    the updated digest.



88
89
90
91
92
93
# File 'lib/junkfood/adler32.rb', line 88

def rollout(b)
  @s1 = (@s1 - b) % BASE
  @s2 = (@s2 - @count * b) % BASE
  @count = @count - 1
  return self.digest
end

#rotate(x1, xn) ⇒ Fixnum

Returns the updated digest.

Parameters:

  • x1 (Byte)
  • xn (Byte)

Returns:

  • (Fixnum)

    the updated digest.



67
68
69
70
71
# File 'lib/junkfood/adler32.rb', line 67

def rotate(x1, xn)
  @s1 = (@s1 - x1 + xn) % BASE
  @s2 = (@s2 - (@count * x1) + @s1 - OFFS) % BASE
  return self.digest
end

#update(data) ⇒ Fixnum

Adds another block of data to digest.

Parameters:

  • data (String)

    block of data to digest.

Returns:

  • (Fixnum)

    the updated digest.



55
56
57
58
59
60
# File 'lib/junkfood/adler32.rb', line 55

def update(data)
  value = Zlib.adler32(data, (@s2 << 16) | @s1)
  @s2, @s1 = (value >> 16) & 0xffff, value & 0xffff
  @count = @count + data.length
  return self.digest
end