github.com/CAFxX/fastrand@v0.1.0/splitmix64_atomic.go (about)

     1  package fastrand
     2  
     3  import (
     4  	"sync/atomic"
     5  )
     6  
     7  // AtomicSplitMix64 implements the Java 8 SplittableRandom generator with atomic state updates.
     8  //
     9  // This generator is safe for concurrent use by multiple goroutines.
    10  // The zero value is a valid state: Seed() can be called to set a custom seed.
    11  type AtomicSplitMix64 struct {
    12  	SplitMix64
    13  }
    14  
    15  // Seed initializes the state with the provided seed.
    16  //
    17  // This function is safe for concurrent use by multiple goroutines.
    18  func (r *AtomicSplitMix64) Seed(s uint64) {
    19  	var t SplitMix64
    20  	t.Seed(s)
    21  	atomic.StoreUint64(&r.state, t.state)
    22  }
    23  
    24  // Uint64 returns a random uint64.
    25  //
    26  // This function is safe for concurrent use by multiple goroutines.
    27  func (r *AtomicSplitMix64) Uint64() uint64 {
    28  	z := atomic.AddUint64(&r.state, 0x9e3779b97f4a7c15)
    29  	z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
    30  	z = (z ^ (z >> 27)) * 0x94d049bb133111eb
    31  	return z ^ (z >> 31)
    32  }