From fb13942b1e64084f5dbea042e224ff1aa26fec64 Mon Sep 17 00:00:00 2001 From: Alexander Morozov Date: Tue, 28 Jul 2015 17:14:49 -0700 Subject: [PATCH] Add global instance of *(math/rand).Rand and Reader You can read random bytes from Reader without exhausting entropy. Signed-off-by: Alexander Morozov --- random/random.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/random/random.go b/random/random.go index 05b7f7f..865f5f3 100644 --- a/random/random.go +++ b/random/random.go @@ -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 + } + } +}