Fix: first time generate same key
This commit is contained in:
parent
1f239cc0c2
commit
8c6c1fa8c3
20
main.go
20
main.go
@ -30,11 +30,6 @@ type redisPoolConf struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
const (
|
|
||||||
letterIdxBits = 6 // 6 bits to represent a letter index
|
|
||||||
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
|
|
||||||
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
|
|
||||||
)
|
|
||||||
|
|
||||||
const defaultPort int = 8002
|
const defaultPort int = 8002
|
||||||
const defaultExpire = 90
|
const defaultExpire = 90
|
||||||
@ -173,19 +168,10 @@ func longToShort(longUrl string, ttl int) string {
|
|||||||
func generate(bits int) string {
|
func generate(bits int) string {
|
||||||
b := make([]byte, bits)
|
b := make([]byte, bits)
|
||||||
|
|
||||||
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
|
currentTime := time.Now().Unix()
|
||||||
for i, cache, remain := bits-1, rand.Int63(), letterIdxMax; i >= 0; {
|
for i := range b {
|
||||||
if remain == 0 {
|
b[i] = letterBytes[(currentTime + rand.Int63()) % int64(len(letterBytes))]
|
||||||
cache, remain = rand.Int63(), letterIdxMax
|
|
||||||
}
|
}
|
||||||
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
|
||||||
b[i] = letterBytes[idx]
|
|
||||||
i--
|
|
||||||
}
|
|
||||||
cache >>= letterIdxBits
|
|
||||||
remain--
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user