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

@@ -10,18 +10,28 @@ import (
"github.com/howeyc/crc16"
)
type CRC16Mode int
const (
CCITT CRC16Mode = iota
CCITT_FALSE
SCSI
IBM
MBUS
)
// 根据给定的校验表类型生成对应的校验器
func hasherSelect(table string) crc16.Hash16 {
switch table {
case "CCITT":
func hasherSelect(mdoe CRC16Mode) crc16.Hash16 {
switch mdoe {
case CCITT:
return crc16.NewCCITT()
case "CCITT-FALSE":
case CCITT_FALSE:
return crc16.New(crc16.MakeTable(crc16.CCITTFalse))
case "SCSI":
case SCSI:
return crc16.NewSCSI()
case "IBM":
case IBM:
return crc16.NewIBM()
case "MBUS":
case MBUS:
return crc16.New(crc16.MakeTable(crc16.MBUS))
default:
return crc16.NewIBM()
@@ -29,27 +39,27 @@ func hasherSelect(table string) crc16.Hash16 {
}
// 计算给定字节数组的CRC16校验和返回字节数组
func CRC16(data []byte, table ...string) []byte {
crcTable := append(table, "IBM")
func CRC16(data []byte, mode ...CRC16Mode) []byte {
crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0])
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的CRC16校验和返回十六进制字符串
func CRC16Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC16(data, table...))
func CRC16Hex(data []byte, mode ...CRC16Mode) string {
return hex.EncodeToString(CRC16(data, mode...))
}
// 计算指定文件的CRC16校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) {
func SumFile(file string, mode ...CRC16Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(table, "IBM")
crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
@@ -58,8 +68,8 @@ func SumFile(file string, table ...string) ([]byte, error) {
}
// 计算指定文件的CRC16校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) {
hash, err := SumFile(file, table...)
func SumFileHex(file string, mode ...CRC16Mode) (string, error) {
hash, err := SumFile(file, mode...)
if err != nil {
return "", err
}