v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/fastrand/u64.go (about)

     1  package fastrand
     2  
     3  // This file contains the implementation of the xorshift128+ algorithm.
     4  // The algorithm is described in: https://vigna.di.unimi.it/ftp/papers/xorshiftplus.pdf
     5  func xorshift128plus(state *[2]uint64) uint64 {
     6  	var x, y, result uint64
     7  	x, y = state[1], state[0]
     8  	result = x + y
     9  	state[0] = x
    10  	y ^= y << 23
    11  	state[1] = x ^ y ^ (x >> 5) ^ (y >> 18)
    12  	return result
    13  }
    14  
    15  func (rng *RNG) Uint64() uint64 {
    16  	return xorshift128plus(&rng.state)
    17  }
    18  
    19  func (rng *RNG) Uint64n(n uint64) uint64 {
    20  	return xorshift128plus(&rng.state) % n
    21  }
    22  
    23  func (rng *RNG) Int64() int64 {
    24  	return int64(rng.Uint64())
    25  }
    26  
    27  func (rng *RNG) Int63() int64 {
    28  	return int64(rng.Uint64() & (1<<63 - 1))
    29  }
    30  
    31  func (rng *RNG) Int63n(n int64) int64 {
    32  	return int64(rng.Uint64n(uint64(n)))
    33  }
    34  
    35  func Uint64() uint64 {
    36  	r := AcquireRNG()
    37  	v := r.Uint64()
    38  	ReleaseRNG(r)
    39  	return v
    40  }
    41  
    42  func Uint64n(n uint64) uint64 {
    43  	r := AcquireRNG()
    44  	v := r.Uint64n(n)
    45  	ReleaseRNG(r)
    46  	return v
    47  }
    48  
    49  func Int64() int64 {
    50  	r := AcquireRNG()
    51  	v := r.Int64()
    52  	ReleaseRNG(r)
    53  	return v
    54  }
    55  
    56  func Int63() int64 {
    57  	r := AcquireRNG()
    58  	v := r.Int63()
    59  	ReleaseRNG(r)
    60  	return v
    61  }
    62  
    63  func Int63n(n int64) int64 {
    64  	r := AcquireRNG()
    65  	v := r.Int63n(n)
    66  	ReleaseRNG(r)
    67  	return v
    68  }