-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.go
45 lines (39 loc) · 1.19 KB
/
source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package gopherng
import (
"encoding/binary"
"fmt"
)
// PseudorandomSource is a pseudorandom source implementing both rand.Source
// and rand.Source64, and can be used to initialize a rand.Rand.
type PseudorandomSource struct {
randReader *PseudorandomReader
}
// NewSource returns a new Source for the given seed. See NewReader() for
// seeding details.
func NewSource(seed []byte) *PseudorandomSource {
return &PseudorandomSource{
randReader: NewReader(seed),
}
}
// Int63 returns an int64 from the internal PseudorandomReader.
func (s *PseudorandomSource) Int63() int64 {
v := int64(s.Uint64())
if v < 0 {
v *= -1
}
return v
}
// Seed exists to be compatible with rand.Source, but is not implemented and
// will panic if called. It should not be needed for use with rand.Rand
// methods.
func (s *PseudorandomSource) Seed(seed int64) {
panic(fmt.Errorf("Seed not supported for gopherng PseudorandomSource"))
}
// Uint64 returns a uint64 from the internal PseudorandomReader.
func (s *PseudorandomSource) Uint64() uint64 {
r := make([]byte, 8)
if _, err := s.randReader.Read(r); err != nil {
panic(fmt.Errorf("unexpected reader error: %w", err))
}
return binary.LittleEndian.Uint64(r)
}