randpool.go 738 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package randpool
  2. import (
  3. crand "crypto/rand"
  4. "encoding/binary"
  5. "fmt"
  6. "math/rand"
  7. "sync"
  8. )
  9. type RandPool struct {
  10. pool sync.Pool
  11. }
  12. var defaultPool = New()
  13. func Borrow(f func(*rand.Rand)) {
  14. defaultPool.Borrow(f)
  15. }
  16. func MakeRand() *rand.Rand {
  17. var seedBuf [8]byte
  18. if _, err := crand.Read(seedBuf[:]); err != nil {
  19. panic(fmt.Errorf("crypto/rand.Read failed: %w", err))
  20. }
  21. uSeed := binary.BigEndian.Uint64(seedBuf[:])
  22. return rand.New(rand.NewSource(int64(uSeed)))
  23. }
  24. func poolMakeRand() any {
  25. return MakeRand()
  26. }
  27. func New() *RandPool {
  28. return &RandPool{
  29. pool: sync.Pool{
  30. New: poolMakeRand,
  31. },
  32. }
  33. }
  34. func (p *RandPool) Borrow(f func(*rand.Rand)) {
  35. rng := p.pool.Get().(*rand.Rand)
  36. defer p.pool.Put(rng)
  37. f(rng)
  38. }