-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_string_generator.go
57 lines (49 loc) · 1.09 KB
/
random_string_generator.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
package repository
import (
"bytes"
"crypto/rand"
"encoding/hex"
"io"
"sync"
)
type RandStringGenerator struct {
randMu sync.Mutex
randReader io.Reader
byteLen uint
bufPool sync.Pool
encoderFactory func(r io.Writer) io.Writer
}
func NewRandStringGenerator(seed int64, byteLen uint, encoderFactory func(r io.Writer) io.Writer) *RandStringGenerator {
if encoderFactory == nil {
encoderFactory = hex.NewEncoder
}
return &RandStringGenerator{
randReader: rand.Reader,
byteLen: byteLen,
bufPool: sync.Pool{
New: func() any {
buf := bytes.NewBuffer(make([]byte, 0, int(byteLen)))
return buf
},
},
encoderFactory: encoderFactory,
}
}
func (f *RandStringGenerator) Generate() (randomStr string, err error) {
buf := f.bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
f.bufPool.Put(buf)
}()
encoder := f.encoderFactory(buf)
f.randMu.Lock()
_, err = io.CopyN(encoder, f.randReader, int64(f.byteLen))
f.randMu.Unlock()
if cl, ok := encoder.(io.Closer); ok {
cl.Close()
}
if err != nil {
return
}
return buf.String(), nil
}