Skip to content

Commit

Permalink
Add global instance of *(math/rand).Rand and Reader
Browse files Browse the repository at this point in the history
You can read random bytes from Reader without exhausting entropy.

Signed-off-by: Alexander Morozov <[email protected]>
  • Loading branch information
LK4D4 committed Jul 29, 2015
1 parent f809037 commit 6963b9c
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions pkg/random/random.go
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
}
}
}

0 comments on commit 6963b9c

Please sign in to comment.