diff --git a/internal/commands/keys.go b/internal/commands/keys.go index 61f000d..ea22edd 100644 --- a/internal/commands/keys.go +++ b/internal/commands/keys.go @@ -106,7 +106,7 @@ func CalcSlots(keys []string) []int { if len(hashtag) > 0 { key = hashtag } - slots[inx] = int(utils.Crc16(key) & 0x3fff) + slots[inx] = int(utils.KeyHash(key) & 0x3fff) } return slots } diff --git a/internal/utils/crc16.go b/internal/utils/crc16.go index 8aa400b..243e6fb 100644 --- a/internal/utils/crc16.go +++ b/internal/utils/crc16.go @@ -81,8 +81,13 @@ var crc16tab = [256]uint16{ func Crc16(buf string) uint16 { var crc uint16 - for _, n := range buf { + bytesBuf := []byte(buf) + for _, n := range bytesBuf { crc = (crc << uint16(8)) ^ crc16tab[((crc>>uint16(8))^uint16(n))&0x00FF] } return crc } + +func KeyHash(buf string) uint16 { + return Crc16(buf) & 0x3FFF +} diff --git a/internal/utils/crc_test.go b/internal/utils/crc_test.go new file mode 100644 index 0000000..bc368ae --- /dev/null +++ b/internal/utils/crc_test.go @@ -0,0 +1,10 @@ +package utils + +import "testing" + +func TestCrc16(t *testing.T) { + ret := KeyHash("你") + if ret != 8522 { + t.Errorf("KeyHash failed, expect: %d, actual: %d", 8522, ret) + } +}