Skip to content

Instantly share code, notes, and snippets.

@magical
Created August 10, 2016 00:40
Show Gist options
  • Save magical/874f8481d51655daf5a3a711c873a54c to your computer and use it in GitHub Desktop.
Save magical/874f8481d51655daf5a3a711c873a54c to your computer and use it in GitHub Desktop.
An implementation of rand.Source which reads from an io.Reader
package main
import (
"fmt"
"io"
"math/rand"
"strings"
)
type ReaderSource struct {
io.Reader
buf [8]byte
}
func (s ReaderSource) Seed(seed int64) {}
func (s ReaderSource) Int63() int64 {
_, err := io.ReadFull(s.Reader, s.buf[:8])
if err != nil {
panic("ReaderSource: read failed")
}
v := int64(s.buf[0])<<0 + int64(s.buf[1])<<8 + int64(s.buf[2])<<16 + int64(s.buf[3])<<24 +
int64(s.buf[4])<<32 + int64(s.buf[5])<<40 + int64(s.buf[6])<<48 + int64(s.buf[7]&^0x80)<<56
return v
}
func main() {
s := ReaderSource{Reader: strings.NewReader(strings.Repeat("\xff", 16))}
r := rand.New(s)
fmt.Println(r.Int63())
fmt.Println(r.Int63())
fmt.Println(r.Int63())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment