bytesource.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2014 Google Inc. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package bytesource provides a rand.Source64 that is determined by a slice of bytes.
  14. package bytesource
  15. import (
  16. "bytes"
  17. "encoding/binary"
  18. "io"
  19. "math/rand"
  20. )
  21. // ByteSource implements rand.Source64 determined by a slice of bytes. The random numbers are
  22. // generated from each 8 bytes in the slice, until the last bytes are consumed, from which a
  23. // fallback pseudo random source is created in case more random numbers are required.
  24. // It also exposes a `bytes.Reader` API, which lets callers consume the bytes directly.
  25. type ByteSource struct {
  26. *bytes.Reader
  27. fallback rand.Source
  28. }
  29. // New returns a new ByteSource from a given slice of bytes.
  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. func (s *ByteSource) Uint64() uint64 {
  41. // Return from input if it was not exhausted.
  42. if s.Len() > 0 {
  43. return s.consumeUint64()
  44. }
  45. // Input was exhausted, return random number from fallback (in this case fallback should not be
  46. // nil). Try first having a Uint64 output (Should work in current rand implementation),
  47. // otherwise return a conversion of Int63.
  48. if s64, ok := s.fallback.(rand.Source64); ok {
  49. return s64.Uint64()
  50. }
  51. return uint64(s.fallback.Int63())
  52. }
  53. func (s *ByteSource) Int63() int64 {
  54. return int64(s.Uint64() >> 1)
  55. }
  56. func (s *ByteSource) Seed(seed int64) {
  57. s.fallback = rand.NewSource(seed)
  58. s.Reader = bytes.NewReader(nil)
  59. }
  60. // consumeUint64 reads 8 bytes from the input and convert them to a uint64. It assumes that the the
  61. // bytes reader is not empty.
  62. func (s *ByteSource) consumeUint64() uint64 {
  63. var bytes [8]byte
  64. _, err := s.Read(bytes[:])
  65. if err != nil && err != io.EOF {
  66. panic("failed reading source") // Should not happen.
  67. }
  68. return binary.BigEndian.Uint64(bytes[:])
  69. }