refactor(crc):重构CRC系列算法中对于模式的定义,限制其取值。
This commit is contained in:
@@ -9,14 +9,22 @@ import (
|
||||
"os"
|
||||
)
|
||||
|
||||
type CRC32Mode int
|
||||
|
||||
const (
|
||||
IEEE CRC32Mode = iota
|
||||
Castagnoli
|
||||
Koopman
|
||||
)
|
||||
|
||||
// 选择一个CRC32校验表
|
||||
func tableSelect(table string) *crc32.Table {
|
||||
switch table {
|
||||
case "IEEE":
|
||||
func tableSelect(mode CRC32Mode) *crc32.Table {
|
||||
switch mode {
|
||||
case IEEE:
|
||||
return crc32.IEEETable
|
||||
case "Castagnoli":
|
||||
case Castagnoli:
|
||||
return crc32.MakeTable(crc32.Castagnoli)
|
||||
case "Koopman":
|
||||
case Koopman:
|
||||
return crc32.MakeTable(crc32.Koopman)
|
||||
default:
|
||||
return crc32.IEEETable
|
||||
@@ -24,27 +32,27 @@ func tableSelect(table string) *crc32.Table {
|
||||
}
|
||||
|
||||
// 计算给定字节数组的CRC32校验和,返回字节数组
|
||||
func CRC32(data []byte, table ...string) []byte {
|
||||
crcTable := append(table, "IEEE")
|
||||
func CRC32(data []byte, mode ...CRC32Mode) []byte {
|
||||
crcTable := append(mode, IEEE)
|
||||
hasher := crc32.New(tableSelect(crcTable[0]))
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的CRC32校验和,返回十六进制字符串
|
||||
func CRC32Hex(data []byte, table ...string) string {
|
||||
return hex.EncodeToString(CRC32(data, table...))
|
||||
func CRC32Hex(data []byte, mode ...CRC32Mode) string {
|
||||
return hex.EncodeToString(CRC32(data, mode...))
|
||||
}
|
||||
|
||||
// 计算指定文件的CRC32校验和,返回字节数组
|
||||
func SumFile(file string, table ...string) ([]byte, error) {
|
||||
func SumFile(file string, mode ...CRC32Mode) ([]byte, error) {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("未能打开指定文件,%w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
crcTable := append(table, "IEEE")
|
||||
crcTable := append(mode, IEEE)
|
||||
hasher := crc32.New(tableSelect(crcTable[0]))
|
||||
if _, err := io.Copy(hasher, f); err != nil {
|
||||
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
|
||||
@@ -53,8 +61,8 @@ func SumFile(file string, table ...string) ([]byte, error) {
|
||||
}
|
||||
|
||||
// 计算指定文件的CRC32校验和,返回十六进制字符串
|
||||
func SumFileHex(file string, table ...string) (string, error) {
|
||||
hash, err := SumFile(file, table...)
|
||||
func SumFileHex(file string, mode ...CRC32Mode) (string, error) {
|
||||
hash, err := SumFile(file, mode...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
Reference in New Issue
Block a user