-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrand_gen.go
88 lines (68 loc) · 2.02 KB
/
rand_gen.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
79
80
81
82
83
84
85
86
87
88
// Package tg is a token generator.
package tg
import (
"errors"
"math/rand"
"strings"
"time"
)
// None represents no character set.
const None = 0
// Lower represents the lowercase character set.
const Lower = 1 << 0
// Upper represents the uppercase character set.
const Upper = 1 << 1
// Digit represents the numeric character set.
const Digit = 1 << 2
// Punct represents the punctuation character set.
const Punct = 1 << 3
// LowerUpper represents the lowercase and uppercase character sets.
const LowerUpper = Lower | Upper
// LowerDigit represents the lowercase and numeric character sets.
const LowerDigit = Lower | Digit
// UpperDigit represents the uppercase and numeric character sets.
const UpperDigit = Upper | Digit
// LowerUpperDigit represents the lowercase, uppercase, and numeric character sets.
const LowerUpperDigit = LowerUpper | Digit
// All represents all character sets, including lowercase, uppercase, numeric, and punctuation.
const All = LowerUpperDigit | Punct
// lower represents the lowercase characters.
const lower = "abcdefghijklmnopqrstuvwxyz"
// upper represents the uppercase characters.
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// digit represents the numeric characters.
const digit = "0123456789"
// punct represents the punctuation characters.
const punct = "~!@#$%^&*()_+-="
// RandGen generates a random string of specified size, using the specified character set and exclusion criteria.
func RandGen(size int, set int, include string, exclude string) (string, error) {
src := rand.NewSource(time.Now().UnixNano())
rnd := rand.New(src)
all := include
if set&Lower > 0 {
all += lower
}
if set&Upper > 0 {
all += upper
}
if set&Digit > 0 {
all += digit
}
if set&Punct > 0 {
all += punct
}
lenAll := len(all)
if len(exclude) >= lenAll {
return "", errors.New("too much to exclude")
}
buf := make([]byte, size)
for i := 0; i < size; i++ {
b := all[rnd.Intn(lenAll)]
if strings.Contains(exclude, string(b)) {
i--
continue
}
buf[i] = b
}
return string(buf), nil
}