golib/helper/uniq_helper.go

52 lines
981 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// uniq_helper.go
// Copyright (C) 2023 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package helper
import (
"git.hexq.cn/tiglog/golib/crypto/gmd5"
"github.com/rs/xid"
)
// 唯一字符串
// 返回字符串长度为 20
func GenId() string {
guid := xid.New()
return guid.String()
}
// 可变长度的唯一字符串
// 长度太短,可能就不唯一了
// 长度大于等于 16 为最佳
// 长度小于20时为 GenId 的值 md5 后的前缀因此理论上前6位也能在大多数情况
// 下唯一
func Uniq(l int) string {
if l <= 0 {
panic("wrong length param")
}
ret := GenId()
hl := len(ret)
if l < hl {
t, err := gmd5.EncryptString(ret)
if err != nil {
return ret[hl-l:]
}
return t[:l]
}
mhac_len := 6
pl := len(ret)
var hash string
for l > pl {
hash = GenId()
hash = hash[mhac_len:]
ret += hash
pl += len(hash)
}
// log.Println("ret=", ret, ", pl=", pl, ", l=", l)
return ret[0:l]
}