...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package bytesource
16
17 import (
18 "bytes"
19 "encoding/binary"
20 "io"
21 "math/rand"
22 )
23
24 type ByteSource struct {
25 *bytes.Reader
26 fallback rand.Source
27 }
28
29
30 func New(input []byte) *ByteSource {
31 s := &ByteSource{
32 Reader: bytes.NewReader(input),
33 fallback: rand.NewSource(0),
34 }
35 if len(input) > 0 {
36 s.fallback = rand.NewSource(int64(s.consumeUint64()))
37 }
38 return s
39 }
40
41 func (s *ByteSource) Uint64() uint64 {
42
43 if s.Len() > 0 {
44 return s.consumeUint64()
45 }
46
47
48
49
50 if s64, ok := s.fallback.(rand.Source64); ok {
51 return s64.Uint64()
52 }
53 return uint64(s.fallback.Int63())
54 }
55
56 func (s *ByteSource) Int63() int64 {
57 return int64(s.Uint64() >> 1)
58 }
59
60 func (s *ByteSource) Seed(seed int64) {
61 s.fallback = rand.NewSource(seed)
62 s.Reader = bytes.NewReader(nil)
63 }
64
65
66
67 func (s *ByteSource) consumeUint64() uint64 {
68 var bytes [8]byte
69 _, err := s.Read(bytes[:])
70 if err != nil && err != io.EOF {
71 panic("failed reading source")
72 }
73 return binary.BigEndian.Uint64(bytes[:])
74 }
75
View as plain text