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:
Alexander Morozov 2015-07-28 17:14:49 -07:00
parent 26a545e3bc
commit fb13942b1e

View file

@ -1,11 +1,19 @@
package random
import (
"io"
"math/rand"
"sync"
"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
type lockedSource struct {
lk sync.Mutex
@ -32,3 +40,22 @@ func NewSource() rand.Source {
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
}
}
}