- Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathrand.go
55 lines (44 loc) · 1.19 KB
/
rand.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
package ksuid
import (
cryptoRand "crypto/rand"
"encoding/binary"
"io"
"math/rand"
)
// FastRander is an io.Reader that uses math/rand and is optimized for
// generating 16 bytes KSUID payloads. It is intended to be used as a
// performance improvements for programs that have no need for
// cryptographically secure KSUIDs and are generating a lot of them.
varFastRander=newRBG()
funcnewRBG() io.Reader {
r, err:=newRandomBitsGenerator()
iferr!=nil {
panic(err)
}
returnr
}
funcnewRandomBitsGenerator() (r io.Reader, errerror) {
varseedint64
ifseed, err=readCryptoRandomSeed(); err!=nil {
return
}
r=&randSourceReader{source: rand.NewSource(seed).(rand.Source64)}
return
}
funcreadCryptoRandomSeed() (seedint64, errerror) {
varb [8]byte
if_, err=io.ReadFull(cryptoRand.Reader, b[:]); err!=nil {
return
}
seed=int64(binary.LittleEndian.Uint64(b[:]))
return
}
typerandSourceReaderstruct {
source rand.Source64
}
func (r*randSourceReader) Read(b []byte) (int, error) {
// optimized for generating 16 bytes payloads
binary.LittleEndian.PutUint64(b[:8], r.source.Uint64())
binary.LittleEndian.PutUint64(b[8:], r.source.Uint64())
return16, nil
}