-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrc32.go
More file actions
91 lines (74 loc) · 2.37 KB
/
crc32.go
File metadata and controls
91 lines (74 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Package crc32itu implements the ITU I.363.5 CRC-32 algorithm (also known as
// AAL5 CRC). This algorithm was popularised by BZIP2 and is also used in ATM
// transmissions.
//
// This package is particularly useful for interoperability with PHP, as it
// produces the same output as PHP's hash('crc32', ...) function. Go's standard
// library hash/crc32 uses a different polynomial and bit ordering, making it
// incompatible with PHP's crc32 hash.
//
// The polynomial used is 0x04C11DB7, with reversed bit shifts compared to the
// IEEE polynomial used in hash/crc32.
//
// The algorithm is the same as that in POSIX 1003.2-1992 cksum, except cksum
// appends the message length to the CRC at the end.
package crc32itu
import "hash"
// Copyright 2011 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.
// Code extracted from golang compress/bzip2
// Size is the size of a CRC-32 checksum in bytes.
const Size = 4
var crctab [256]uint32
func init() {
const poly = 0x04C11DB7
for i := range crctab {
crc := uint32(i) << 24
for j := 0; j < 8; j++ {
if crc&0x80000000 != 0 {
crc = (crc << 1) ^ poly
} else {
crc <<= 1
}
}
crctab[i] = crc
}
}
// updateCRC updates the crc value to incorporate the data in b.
// The initial value is 0.
func updateCRC(val uint32, b []byte) uint32 {
crc := ^val
for _, v := range b {
crc = crctab[byte(crc>>24)^v] ^ (crc << 8)
}
return ^crc
}
// Checksum returns the ITU I.363.5 checksum of data.
func Checksum(data []byte) uint32 {
return updateCRC(0, data)
}
// Update returns the result of adding the bytes in p to the crc.
func Update(crc uint32, data []byte) uint32 {
return updateCRC(crc, data)
}
// New returns a new instance of hash.Hash32 that can be used to compute CRC32
// values using this standard interface.
func New() hash.Hash32 {
return &crc32digest{}
}
type crc32digest struct {
crc uint32
}
func (d *crc32digest) Size() int { return Size }
func (d *crc32digest) BlockSize() int { return 1 }
func (d *crc32digest) Reset() { d.crc = 0 }
func (d *crc32digest) Sum32() uint32 { return d.crc }
func (d *crc32digest) Sum(in []byte) []byte {
s := d.Sum32()
return append(in, byte(s>>24), byte(s>>16), byte(s>>8), byte(s))
}
func (d *crc32digest) Write(p []byte) (n int, err error) {
d.crc = updateCRC(d.crc, p)
return len(p), nil
}