refactor(crc):重构CRC系列算法中对于模式的定义,限制其取值。

This commit is contained in:
徐涛
2023-07-16 11:45:31 +08:00
parent 732c01e36c
commit 1f99378655
4 changed files with 100 additions and 60 deletions

View File

@@ -9,12 +9,19 @@ import (
"os"
)
type CRC64Mode int
const (
ECMA CRC64Mode = iota
ISO
)
// 选择一个CRC64校验表。
func tableSelect(table string) *crc64.Table {
switch table {
case "ECMA":
func tableSelect(mode CRC64Mode) *crc64.Table {
switch mode {
case ECMA:
return crc64.MakeTable(crc64.ECMA)
case "ISO":
case ISO:
return crc64.MakeTable(crc64.ISO)
default:
return crc64.MakeTable(crc64.ISO)
@@ -22,27 +29,27 @@ func tableSelect(table string) *crc64.Table {
}
// 计算给定字节数组的CRC64校验和返回字节数组。
func CRC64(data []byte, table ...string) []byte {
crcTable := append(table, "ISO")
func CRC64(data []byte, mode ...CRC64Mode) []byte {
crcTable := append(mode, ISO)
hasher := crc64.New(tableSelect(crcTable[0]))
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的CRC64校验和返回十六进制字符串。
func CRC64Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC64(data, table...))
func CRC64Hex(data []byte, mode ...CRC64Mode) string {
return hex.EncodeToString(CRC64(data, mode...))
}
// 计算一个指定文件的CRC64校验和返回字节数组。
func SumFile(file string, table ...string) ([]byte, error) {
func SumFile(file string, mode ...CRC64Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(table, "ISO")
crcTable := append(mode, ISO)
hasher := crc64.New(tableSelect(crcTable[0]))
if _, err := io.Copy(hasher, f); err != nil {
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
@@ -51,8 +58,8 @@ func SumFile(file string, table ...string) ([]byte, error) {
}
// 计算一个指定文件的CRC64校验和返回十六进制字符串。
func SumFileHex(file string, table ...string) (string, error) {
hash, err := SumFile(file, table...)
func SumFileHex(file string, mode ...CRC64Mode) (string, error) {
hash, err := SumFile(file, mode...)
if err != nil {
return "", err
}