-
Notifications
You must be signed in to change notification settings - Fork 0
/
randstr.go
70 lines (59 loc) · 1.5 KB
/
randstr.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
package randstr
import (
errors "errors"
rand "math/rand"
)
const (
// LettersNumStr is numbers from 0 to 9.
LettersNumStr = "0123456789"
// LettersUpperStr is upper case from A to Z.
LettersUpperStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// LettersLowerStr is lower case from a to z.
LettersLowerStr = "abcdefghijklmnopqrstuvwxyz"
)
var (
// ErrZeroLengthLetters is error.
ErrZeroLengthLetters = errors.New("srcLetters must not be zero in length")
)
// RandStr is random string generater.
type RandStr struct {
// srcLetters is source of generated random string.
srcLetters []rune
randModule *rand.Rand
}
// New returns new RandStr.
func New(src rand.Source, letters []rune) *RandStr {
return &RandStr{
randModule: rand.New(src),
srcLetters: letters,
}
}
// Gen generates random string.
func (rs *RandStr) Gen(length uint) string {
l := len(rs.srcLetters)
r := make([]rune, length)
for i := uint(0); i < length; i++ {
r[i] = rs.srcLetters[rs.randModule.Intn(l)]
}
return string(r)
}
// GetSrcLetters gets srcLetters.
func (rs *RandStr) GetSrcLetters() []rune {
return rs.srcLetters
}
// SetSrcLetters sets srcLetters.
func (rs *RandStr) SetSrcLetters(letters []rune) error {
if len(letters) <= 0 {
return ErrZeroLengthLetters
}
rs.srcLetters = letters
return nil
}
// GetRandModule gets randModule.
func (rs *RandStr) GetRandModule() *rand.Rand {
return rs.randModule
}
// SetRandModule sets randModule.
func (rs *RandStr) SetRandModule(newRandModule *rand.Rand) {
rs.randModule = newRandModule
}