api/pkg/utils/random_string.go

50 lines
1.7 KiB
Go
Raw Normal View History

2020-02-07 16:27:45 +00:00
// Vikunja is a to-do list application to facilitate your life.
2021-02-02 19:19:13 +00:00
// Copyright 2018-2021 Vikunja and contributors. All rights reserved.
2018-11-26 20:17:33 +00:00
//
// This program is free software: you can redistribute it and/or modify
2020-12-23 15:41:52 +00:00
// it under the terms of the GNU Affero General Public Licensee as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
2018-11-26 20:17:33 +00:00
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2020-12-23 15:41:52 +00:00
// GNU Affero General Public Licensee for more details.
2018-11-26 20:17:33 +00:00
//
2020-12-23 15:41:52 +00:00
// You should have received a copy of the GNU Affero General Public Licensee
// along with this program. If not, see <https://www.gnu.org/licenses/>.
2018-11-26 20:17:33 +00:00
2018-10-27 09:33:28 +00:00
package utils
import (
"math/rand"
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
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
)
// MakeRandomString return a random string
func MakeRandomString(n int) string {
2023-03-05 21:24:25 +00:00
source := rand.New(rand.NewSource(time.Now().UnixNano()))
2018-10-27 09:33:28 +00:00
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
2023-03-05 21:24:25 +00:00
for i, cache, remain := n-1, source.Int63(), letterIdxMax; i >= 0; {
2018-10-27 09:33:28 +00:00
if remain == 0 {
2023-03-05 21:24:25 +00:00
cache, remain = source.Int63(), letterIdxMax
2018-10-27 09:33:28 +00:00
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}