| 1 |
// +build cgo |
| 2 |
|
| 3 |
/* |
| 4 |
Copyright 2017 Google Inc. |
| 5 |
|
| 6 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 |
you may not use this file except in compliance with the License. |
| 8 |
You may obtain a copy of the License at |
| 9 |
|
| 10 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
|
| 12 |
Unless required by applicable law or agreed to in writing, software |
| 13 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 14 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 |
See the License for the specific language governing permissions and |
| 16 |
limitations under the License. |
| 17 |
*/ |
| 18 |
|
| 19 |
package cgzip |
| 20 |
|
| 21 |
/* |
| 22 |
#cgo CFLAGS: -Werror=implicit |
| 23 |
#cgo pkg-config: zlib |
| 24 |
|
| 25 |
#include "zlib.h" |
| 26 |
*/ |
| 27 |
import "C" |
| 28 |
|
| 29 |
import ( |
| 30 |
"hash" |
| 31 |
"unsafe" |
| 32 |
) |
| 33 |
|
| 34 |
type crc32Hash struct { |
| 35 |
crc C.uLong |
| 36 |
} |
| 37 |
|
| 38 |
// NewCrc32 creates an empty buffer which has an crc32 of '1'. The go |
| 39 |
// hash/crc32 does the same. |
| 40 |
func NewCrc32() hash.Hash32 { |
| 41 |
c := &crc32Hash{} |
| 42 |
c.Reset() |
| 43 |
return c |
| 44 |
} |
| 45 |
|
| 46 |
// io.Writer interface |
| 47 |
func (a *crc32Hash) Write(p []byte) (n int, err error) { |
| 48 |
if len(p) > 0 { |
| 49 |
a.crc = C.crc32(a.crc, (*C.Bytef)(unsafe.Pointer(&p[0])), (C.uInt)(len(p))) |
| 50 |
} |
| 51 |
return len(p), nil |
| 52 |
} |
| 53 |
|
| 54 |
// hash.Hash interface |
| 55 |
func (a *crc32Hash) Sum(b []byte) []byte { |
| 56 |
s := a.Sum32() |
| 57 |
b = append(b, byte(s>>24)) |
| 58 |
b = append(b, byte(s>>16)) |
| 59 |
b = append(b, byte(s>>8)) |
| 60 |
b = append(b, byte(s)) |
| 61 |
return b |
| 62 |
} |
| 63 |
|
| 64 |
func (a *crc32Hash) Reset() { |
| 65 |
a.crc = C.crc32(0, (*C.Bytef)(unsafe.Pointer(nil)), 0) |
| 66 |
} |
| 67 |
|
| 68 |
func (a *crc32Hash) Size() int { |
| 69 |
return 4 |
| 70 |
} |
| 71 |
|
| 72 |
func (a *crc32Hash) BlockSize() int { |
| 73 |
return 1 |
| 74 |
} |
| 75 |
|
| 76 |
// hash.Hash32 interface |
| 77 |
func (a *crc32Hash) Sum32() uint32 { |
| 78 |
return uint32(a.crc) |
| 79 |
} |