Skip to content

Commit

Permalink
[modify] refine AdjustHash
Browse files Browse the repository at this point in the history
  • Loading branch information
shabicheng committed Jun 19, 2020
1 parent 1c01375 commit b50a89f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
46 changes: 46 additions & 0 deletions producer/adjusthash.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,54 @@ import (
"strings"
)

const zero32Str = "00000000000000000000000000000000"

func toHex(x byte) byte {
if x < 10 {
return '0' + x
}
return 'a' - 10 + x
}

func getBitValue(val byte, bits int) byte {
if bits >= 16 {
return val
}
if bits >= 8 {
return val & (0xf - 1)
}
if bits >= 4 {
return val & (0xf - 3)
}
if bits >= 2 {
return val & (0xf - 7)
}
return val & (0xf - 15)
}

func AdjustHash(shardhash string, buckets int) (string, error) {
h := md5.New()
h.Write([]byte(shardhash))
cipherStr := h.Sum(nil)

var destBuf strings.Builder
destBuf.Grow(32)
i := 0

for buckets > 0 && i < len(cipherStr) {
if (i & 0x01) == 0 {
destBuf.WriteByte(toHex(getBitValue(cipherStr[i>>1]>>4, buckets)))
} else {
destBuf.WriteByte(toHex(getBitValue(cipherStr[i>>1]&0xF, buckets)))
}
buckets = buckets >> 4
i++
}
destBuf.WriteString(zero32Str[0 : 32-i])
return destBuf.String(), nil
}

func AdjustHashOld(shardhash string, buckets int) (string, error) {
res := Md5ToBin(ToMd5(shardhash))
x, err := BitCount(buckets)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions producer/adjusthash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ func TestAdjustHash(t *testing.T) {
}
}

func Benchmark_AdjustHash(b *testing.B) {
for i := 0; i < b.N; i++ {
AdjustHash("192.168.0.2", 256)
}
}

func TestBitCount(t *testing.T) {
type args struct {
buckets int
Expand Down

0 comments on commit b50a89f

Please sign in to comment.