Created
April 13, 2018 18:49
-
-
Save rs/5bb99f5ea76122eddb3cea267515abfb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package staticrand | |
import ( | |
"math/rand" | |
"sync/atomic" | |
) | |
const ( | |
_MAX = 1 << 63 | |
_MASK = _MAX - 1 | |
) | |
const randLen = 5000 | |
type Source struct { | |
i int32 | |
r [randLen]uint64 | |
} | |
func (src *Source) Seed(seed int64) { | |
r := rand.New(rand.NewSource(seed)) | |
for i := 0; i < randLen; i++ { | |
src.r[i] = r.Uint64() | |
} | |
} | |
func (src *Source) Int63() int64 { | |
return int64(src.Uint64() & _MASK) | |
} | |
func (src *Source) Uint64() uint64 { | |
i := atomic.AddInt32(&src.i, -1) | |
for i < 0 { | |
old := i | |
i = randLen - 1 | |
if !atomic.CompareAndSwapInt32(&src.i, old, i) { | |
// if swap failed, we got a conflict, try again | |
i = atomic.AddInt32(&src.i, -1) | |
continue | |
} | |
break | |
} | |
return src.r[i] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment