1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// Package adler32 implements the Adler-32 checksum. 6// 7// It is defined in RFC 1950: 8// Adler-32 is composed of two sums accumulated per byte: s1 is 9// the sum of all bytes, s2 is the sum of all s1 values. Both sums 10// are done modulo 65521. s1 is initialized to 1, s2 to zero. The 11// Adler-32 checksum is stored as s2*65536 + s1 in most- 12// significant-byte first (network) order. 13package adler32 14 15import "hash" 16 17const ( 18 // mod is the largest prime that is less than 65536. 19 mod = 65521 20 // nmax is the largest n such that 21 // 255 * n * (n+1) / 2 + (n+1) * (mod-1) <= 2^32-1. 22 // It is mentioned in RFC 1950 (search for "5552"). 23 nmax = 5552 24) 25 26// The size of an Adler-32 checksum in bytes. 27const Size = 4 28 29// digest represents the partial evaluation of a checksum. 30// The low 16 bits are s1, the high 16 bits are s2. 31type digest uint32 32 33func (d *digest) Reset() { *d = 1 } 34 35// New returns a new hash.Hash32 computing the Adler-32 checksum. 36func New() hash.Hash32 { 37 d := new(digest) 38 d.Reset() 39 return d 40} 41 42func (d *digest) Size() int { return Size } 43 44func (d *digest) BlockSize() int { return 1 } 45 46// Add p to the running checksum d. 47func update(d digest, p []byte) digest { 48 s1, s2 := uint32(d&0xffff), uint32(d>>16) 49 for len(p) > 0 { 50 var q []byte 51 if len(p) > nmax { 52 p, q = p[:nmax], p[nmax:] 53 } 54 for _, x := range p { 55 s1 += uint32(x) 56 s2 += s1 57 } 58 s1 %= mod 59 s2 %= mod 60 p = q 61 } 62 return digest(s2<<16 | s1) 63} 64 65func (d *digest) Write(p []byte) (nn int, err error) { 66 *d = update(*d, p) 67 return len(p), nil 68} 69 70func (d *digest) Sum32() uint32 { return uint32(*d) } 71 72func (d *digest) Sum(in []byte) []byte { 73 s := uint32(*d) 74 return append(in, byte(s>>24), byte(s>>16), byte(s>>8), byte(s)) 75} 76 77// Checksum returns the Adler-32 checksum of data. 78func Checksum(data []byte) uint32 { return uint32(update(1, data)) } 79