| // Copyright 2009 The Go Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style | |
| // license that can be found in the LICENSE file. | |
| // This package implements the Adler-32 checksum. | |
| // Defined in RFC 1950: | |
| // Adler-32 is composed of two sums accumulated per byte: s1 is | |
| // the sum of all bytes, s2 is the sum of all s1 values. Both sums | |
| // are done modulo 65521. s1 is initialized to 1, s2 to zero. The | |
| // Adler-32 checksum is stored as s2*65536 + s1 in most- | |
| // significant-byte first (network) order. | |
| package adler32 | |
| import "os" | |
| const ( | |
| mod = 65521; | |
| ) | |
| // Digest represents the partial evaluation of a checksum. | |
| type Digest struct { | |
| // invariant: (a < mod && b < mod) || a <= b | |
| // invariant: a + b + 255 <= 0xffffffff | |
| a, b uint32; | |
| } | |
| // NewDigest creates a new Digest. | |
| func NewDigest() *Digest { | |
| return &Digest{1, 0}; | |
| } | |
| // Write updates the Digest with the incremental checksum generated by p. | |
| // It returns the number of bytes written; err is always nil. | |
| func (d *Digest) Write(p []byte) (nn int, err os.Error) { | |
| a, b := d.a, d.b; | |
| for i := 0; i < len(p); i++ { | |
| a += uint32(p[i]); | |
| b += a; | |
| // invariant: a <= b | |
| if b > (0xffffffff - 255) / 2 { | |
| a %= mod; | |
| b %= mod; | |
| // invariant: a < mod && b < mod | |
| } else { | |
| // invariant: a + b + 255 <= 2 * b + 255 <= 0xffffffff | |
| } | |
| } | |
| d.a, d.b = a, b; | |
| return len(p), nil | |
| } | |
| // Sum32 returns the 32-bit Adler-32 checksum of the data written to the Digest. | |
| func (d *Digest) Sum32() uint32 { | |
| a, b := d.a, d.b; | |
| if b >= mod { | |
| a %= mod; | |
| b %= mod; | |
| } | |
| return b<<16 | a; | |
| } | |
| // Sum returns the 32-bit Adler-32 checksum of the data written to the Digest | |
| // in the form of an array of 4 bytes in big-endian order. | |
| func (d *Digest) Sum() []byte { | |
| p := make([]byte, 4); | |
| s := d.Sum32(); | |
| p[0] = byte(s>>24); | |
| p[1] = byte(s>>16); | |
| p[2] = byte(s>>8); | |
| p[3] = byte(s); | |
| return p; | |
| } |