-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmath.go
80 lines (63 loc) · 1.84 KB
/
math.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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package randutil provides primitives for generating random values
package randutil
import (
mrand "math/rand" // used for non-crypto unique ID and random port selection
"sync"
"time"
)
// MathRandomGenerator is a random generator for non-crypto usage.
type MathRandomGenerator interface {
// Intn returns random integer within [0:n).
Intn(n int) int
// Uint32 returns random 32-bit unsigned integer.
Uint32() uint32
// Uint64 returns random 64-bit unsigned integer.
Uint64() uint64
// GenerateString returns ranom string using given set of runes.
// It can be used for generating unique ID to avoid name collision.
//
// Caution: DO NOT use this for cryptographic usage.
GenerateString(n int, runes string) string
}
type mathRandomGenerator struct {
r *mrand.Rand
mu sync.Mutex
}
// NewMathRandomGenerator creates new mathmatical random generator.
// Random generator is seeded by crypto random.
func NewMathRandomGenerator() MathRandomGenerator {
seed, err := CryptoUint64()
if err != nil {
// crypto/rand is unavailable. Fallback to seed by time.
seed = uint64(time.Now().UnixNano()) //nolint:gosec // G115
}
return &mathRandomGenerator{r: mrand.New(mrand.NewSource(int64(seed)))} //nolint:stylecheck,gosec
}
func (g *mathRandomGenerator) Intn(n int) int {
g.mu.Lock()
v := g.r.Intn(n)
g.mu.Unlock()
return v
}
func (g *mathRandomGenerator) Uint32() uint32 {
g.mu.Lock()
v := g.r.Uint32()
g.mu.Unlock()
return v
}
func (g *mathRandomGenerator) Uint64() uint64 {
g.mu.Lock()
v := g.r.Uint64()
g.mu.Unlock()
return v
}
func (g *mathRandomGenerator) GenerateString(n int, runes string) string {
letters := []rune(runes)
b := make([]rune, n)
for i := range b {
b[i] = letters[g.Intn(len(letters))]
}
return string(b)
}