-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinyid.go
78 lines (64 loc) · 1.93 KB
/
tinyid.go
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
70
71
72
73
74
75
76
77
78
package tinyid
import (
"crypto/rand"
"errors"
"math"
// "math/bits"
// "strings"
)
// Represent the default alphabet and size for the generated tiny IDs.
const (
// Default is the default alphabet for TinyIDs.
DefaultAlphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
// DefaultSize is the default size for Tiny IDs.
DefaultSize = 31
)
// Generate Bytes represents random bytes buffer
// 'step' parameter representing the number of bytes to generate and returns a byte slice and an error
type GenerateBytes func(step int) ([]byte, error)
// Generates a random buffer of bytes using cryptographic randomness
func randomBufferGenerator(step int) ([]byte, error) {
buffer := make([]byte, step)
_, err := rand.Read(buffer)
return buffer, err
}
// GenerateTinyId generates a random sttring based on the alphabet and size.
func generateTinyId(alphabet string, size int) (string, error) {
if size <= 0 {
return "", errors.New("tinyId: size must be greater than 0")
}
// Calculate mask based on alphabet length
mask := len(alphabet) - 1
// Calculate step size based on mask and size
step := int(math.Ceil(1.6 * float64(mask*size) / float64(len(alphabet))))
// Initialize byte slice to hold ID
id := make([]byte, size)
// Generate ID
for i := 0; i < size; {
// Generate random buffer of bytes
randomBuffer, err := randomBufferGenerator(step)
if err != nil {
return "", err
}
// Process random buffer
for _, b := range randomBuffer {
// Map byte to character in alphabet using mask
index := int(b) & mask
// Check if index is within alphabet range
if index < len(alphabet) {
// Add character to ID
id[i] = alphabet[index]
i++
// Check if ID is complete
if i == size {
break
}
}
}
}
return string(id), nil
}
// NewTinyID generates a random string with default settings.
func NewTinyID() (string, error) {
return generateTinyId(DefaultAlphabet, DefaultSize)
}