目录打散hash算法(golang)

由于需要用到目录打散的算法,网上找了一下资料,发现都是java版本的,所以参考了一下写了个go版本的。分享一下

package main

import (
	"fmt"
	"hash/crc32"
    "github.com/google/uuid"
)


func HashMakeDir(name string) (dir int, Subdir int) {
	var (
		hashNumber int
	)
	hashNumber = int(crc32.ChecksumIEEE([]byte(name)))
	if -hashNumber >= 0 {
		hashNumber = -hashNumber
	}

	return hashNumber & 0xf, (hashNumber & 0xf0) >> 4
}


func main() {
    //循环500次查看结果
	for index := 0; index < 500; index++ {
		str := uuid.New().String()
        // 循环3次验证生成是否一致
		for i := 0; i < 3; i++ {
			dir, subDir := util.HashMakeDir(str)
			fmt.Println(fmt.Sprintf("/tmp/%d/%d", dir, subDir))
		}

	}
}

部分打印如下:

/tmp/0/6
/tmp/0/6
/tmp/0/6
/tmp/4/10
/tmp/4/10
/tmp/4/10
/tmp/7/0
/tmp/7/0
/tmp/7/0
/tmp/4/6
/tmp/4/6
/tmp/4/6
/tmp/14/10
/tmp/14/10
/tmp/14/10
/tmp/0/4
/tmp/0/4
/tmp/0/4
/tmp/5/7
/tmp/5/7
/tmp/5/7
/tmp/12/5
/tmp/12/5
/tmp/12/5
/tmp/3/6
/tmp/3/6
/tmp/3/6
/tmp/10/3
/tmp/10/3
/tmp/10/3
/tmp/4/11
/tmp/4/11
/tmp/4/11
/tmp/11/12
/tmp/11/12
/tmp/11/12
/tmp/2/10
/tmp/2/10
/tmp/2/10
/tmp/8/6
/tmp/8/6
/tmp/8/6
/tmp/3/0
/tmp/3/0
/tmp/3/0
/tmp/4/6
/tmp/4/6
/tmp/4/6
/tmp/8/7
/tmp/8/7
/tmp/8/7
/tmp/9/14
/tmp/9/14
/tmp/9/14
/tmp/6/12
/tmp/6/12
/tmp/6/12

你可能感兴趣的:(golang)