Add global instance of *(math/rand).Rand and Reader
You can read random bytes from Reader without exhausting entropy. Signed-off-by: Alexander Morozov <lk4d4@docker.com>
This commit is contained in:
parent
26a545e3bc
commit
fb13942b1e
1 changed files with 27 additions and 0 deletions
|
@ -1,11 +1,19 @@
|
||||||
package random
|
package random
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"io"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Rand is a global *rand.Rand instance, which initilized with NewSource() source.
|
||||||
|
var Rand = rand.New(NewSource())
|
||||||
|
|
||||||
|
// Reader is a global, shared instance of a pseudorandom bytes generator.
|
||||||
|
// It doesn't consume entropy.
|
||||||
|
var Reader io.Reader = &reader{rnd: Rand}
|
||||||
|
|
||||||
// copypaste from standard math/rand
|
// copypaste from standard math/rand
|
||||||
type lockedSource struct {
|
type lockedSource struct {
|
||||||
lk sync.Mutex
|
lk sync.Mutex
|
||||||
|
@ -32,3 +40,22 @@ func NewSource() rand.Source {
|
||||||
src: rand.NewSource(time.Now().UnixNano()),
|
src: rand.NewSource(time.Now().UnixNano()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type reader struct {
|
||||||
|
rnd *rand.Rand
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) Read(b []byte) (int, error) {
|
||||||
|
i := 0
|
||||||
|
for {
|
||||||
|
val := r.rnd.Int63()
|
||||||
|
for val > 0 {
|
||||||
|
b[i] = byte(val)
|
||||||
|
i++
|
||||||
|
if i == len(b) {
|
||||||
|
return i, nil
|
||||||
|
}
|
||||||
|
val >>= 8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue