]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/hash/crc64/crc64.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.git] / libgo / go / hash / crc64 / crc64.go
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 // This package implements the 64-bit cyclic redundancy check, or CRC-64, checksum.
6 // See http://en.wikipedia.org/wiki/Cyclic_redundancy_check for information.
7 package crc64
8
9 import (
10 "hash"
11 "os"
12 )
13
14 // The size of a CRC-64 checksum in bytes.
15 const Size = 8
16
17 // Predefined polynomials.
18 const (
19 // The ISO polynomial, defined in ISO 3309 and used in HDLC.
20 ISO = 0xD800000000000000
21
22 // The ECMA polynomial, defined in ECMA 182.
23 ECMA = 0xC96C5795D7870F42
24 )
25
26 // Table is a 256-word table representing the polynomial for efficient processing.
27 type Table [256]uint64
28
29 // MakeTable returns the Table constructed from the specified polynomial.
30 func MakeTable(poly uint64) *Table {
31 t := new(Table)
32 for i := 0; i < 256; i++ {
33 crc := uint64(i)
34 for j := 0; j < 8; j++ {
35 if crc&1 == 1 {
36 crc = (crc >> 1) ^ poly
37 } else {
38 crc >>= 1
39 }
40 }
41 t[i] = crc
42 }
43 return t
44 }
45
46 // digest represents the partial evaluation of a checksum.
47 type digest struct {
48 crc uint64
49 tab *Table
50 }
51
52 // New creates a new hash.Hash64 computing the CRC-64 checksum
53 // using the polynomial represented by the Table.
54 func New(tab *Table) hash.Hash64 { return &digest{0, tab} }
55
56 func (d *digest) Size() int { return Size }
57
58 func (d *digest) Reset() { d.crc = 0 }
59
60 func update(crc uint64, tab *Table, p []byte) uint64 {
61 crc = ^crc
62 for _, v := range p {
63 crc = tab[byte(crc)^v] ^ (crc >> 8)
64 }
65 return ^crc
66 }
67
68 // Update returns the result of adding the bytes in p to the crc.
69 func Update(crc uint64, tab *Table, p []byte) uint64 {
70 return update(crc, tab, p)
71 }
72
73 func (d *digest) Write(p []byte) (n int, err os.Error) {
74 d.crc = update(d.crc, d.tab, p)
75 return len(p), nil
76 }
77
78 func (d *digest) Sum64() uint64 { return d.crc }
79
80 func (d *digest) Sum() []byte {
81 p := make([]byte, 8)
82 s := d.Sum64()
83 p[0] = byte(s >> 54)
84 p[1] = byte(s >> 48)
85 p[2] = byte(s >> 40)
86 p[3] = byte(s >> 32)
87 p[4] = byte(s >> 24)
88 p[5] = byte(s >> 16)
89 p[6] = byte(s >> 8)
90 p[7] = byte(s)
91 return p
92 }
93
94 // Checksum returns the CRC-64 checksum of data
95 // using the polynomial represented by the Table.
96 func Checksum(data []byte, tab *Table) uint64 { return update(0, tab, data) }