Class: Junkfood::Adler32Pure

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

Overview

A pure Ruby implementation of the Adler-32 checksum algorithm.

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

Examples:

adler32 = Junkfood::Adler32Pure.new('Wikipedia')
puts adler32.digest #=> 300286872

See Also:

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 = '') ⇒ Adler32Pure

Returns a new instance of Adler32Pure.

Parameters:

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

    initial block of data to digest.



44
45
46
47
48
49
# File 'lib/junkfood/adler32_pure.rb', line 44

def initialize(data='')
  @count = 0
  @s2 = 0
  @s1 = OFFS
  self.update(data)
end

Instance Method Details

#digestFixnum

Returns the current Adler32 digest value.

Returns:

  • (Fixnum)

    the current Adler32 digest value.



108
109
110
# File 'lib/junkfood/adler32_pure.rb', line 108

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

#rollin(b) ⇒ Fixnum

Returns the updated digest.

Parameters:

  • b (Byte)

Returns:

  • (Fixnum)

    the updated digest.



87
88
89
90
91
92
# File 'lib/junkfood/adler32_pure.rb', line 87

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.



98
99
100
101
102
103
# File 'lib/junkfood/adler32_pure.rb', line 98

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.



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

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.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/junkfood/adler32_pure.rb', line 57

def update(data)
  i = 0
  while i < data.length
    data[i,i+NMAX].each_byte do |b|
      @s1 = @s1 + b
      @s2 = @s2 + @s1
    end
    @s1 = @s1 % BASE
    @s2 = @s2 % BASE
    i = i + NMAX
  end
  @count = @count + data.length
  return self.digest
end