rng.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. Copyright 2014 Zachary Klippenstein
  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 regen
  14. /*
  15. The default Source implementation is very slow to seed. Replaced with a
  16. 64-bit xor-shift source from http://vigna.di.unimi.it/ftp/papers/xorshift.pdf.
  17. This source seeds very quickly, and only uses a single variable, so concurrent
  18. modification by multiple goroutines is possible.
  19. To create a seeded source:
  20. randSource := xorShift64Source(mySeed)
  21. To create a source with the default seed:
  22. var randSource xorShift64Source
  23. */
  24. type xorShift64Source uint64
  25. func (src *xorShift64Source) Seed(seed int64) {
  26. *src = xorShift64Source(seed)
  27. }
  28. func (src *xorShift64Source) Int63() int64 {
  29. // A zero seed will only generate zeros.
  30. if *src == 0 {
  31. *src = 1
  32. }
  33. *src ^= *src >> 12 // a
  34. *src ^= *src << 25 // b
  35. *src ^= *src >> 27 // c
  36. return int64((*src * 2685821657736338717) >> 1)
  37. }