This repository was archived by the owner on May 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathnanoid.go
More file actions
69 lines (58 loc) · 1.74 KB
/
nanoid.go
File metadata and controls
69 lines (58 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Package nanoid provides fast and convenient unique string generator.
package nanoid
import (
"crypto/rand"
"math"
"math/bits"
"strings"
)
const (
// DefaultAlphabet is the default alphabet for Nano ID.
DefaultAlphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
// DefaultSize is the default size for Nano ID.
DefaultSize = 21
)
// BytesGenerator represents random bytes buffer.
type BytesGenerator func(step int) ([]byte, error)
func generateRandomBuffer(step int) ([]byte, error) {
buffer := make([]byte, step)
if _, err := rand.Read(buffer); err != nil {
return nil, err
}
return buffer, nil
}
// FormatString generates a random string based on BytesGenerator, alphabet and size.
func FormatString(generateRandomBuffer BytesGenerator, alphabet string, size int) (string, error) {
mask := 2<<uint32(31-bits.LeadingZeros32(uint32(len(alphabet)-1|1))) - 1
step := int(math.Ceil(1.6 * float64(mask*size) / float64(len(alphabet))))
id := new(strings.Builder)
id.Grow(size)
for {
randomBuffer, err := generateRandomBuffer(step)
if err != nil {
return "", err
}
for i := 0; i < step; i++ {
currentIndex := int(randomBuffer[i]) & mask
if currentIndex < len(alphabet) {
if err := id.WriteByte(alphabet[currentIndex]); err != nil {
return "", err
} else if id.Len() == size {
return id.String(), nil
}
}
}
}
}
// GenerateString generates a random string based on alphabet and size.
func GenerateString(alphabet string, size int) (string, error) {
id, err := FormatString(generateRandomBuffer, alphabet, size)
if err != nil {
return "", err
}
return id, nil
}
// New generates a random string.
func New() (string, error) {
return GenerateString(DefaultAlphabet, DefaultSize)
}