-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerator.go
More file actions
64 lines (49 loc) 路 987 Bytes
/
Copy pathgenerator.go
File metadata and controls
64 lines (49 loc) 路 987 Bytes
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
package gopass
import (
"bytes"
"crypto/rand"
"math/big"
)
var DefaultOptions = []Option{Numbers(), Letters()}
type Generator struct {
chars bytes.Buffer
}
func New(opts ...Option) Gopass {
g := &Generator{}
g.With(opts...)
return g
}
func (g *Generator) Generate(length int) []byte {
if length <= 0 {
return nil
}
buf := newBuffer()
defer releaseBuffer(buf)
g.generate(buf, length)
return buf.Bytes()
}
func (g *Generator) GenerateString(length int) string {
if length <= 0 {
return ""
}
buf := newBuffer()
defer releaseBuffer(buf)
g.generate(buf, length)
return buf.String()
}
func (g *Generator) With(opts ...Option) {
g.chars.Reset()
if len(opts) == 0 {
opts = DefaultOptions
}
for _, opt := range opts {
opt(g)
}
}
func (g *Generator) generate(buf *bytes.Buffer, length int) {
max := big.NewInt(int64(g.chars.Len()))
for i := 0; i < length; i++ {
n, _ := rand.Int(rand.Reader, max)
buf.WriteByte(g.chars.Bytes()[n.Int64()])
}
}