1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package internal
import (
"math/rand"
"sync"
"time"
)
var (
seededRand = struct {
sync.Mutex
*rand.Rand
}{
Rand: rand.New(rand.NewSource(int64(time.Now().UnixNano()))),
}
)
// RandUint64 returns a random uint64.
//
// IMPORTANT! The default rand package functions are not used, since we want to
// minimize the chance that different Go processes duplicate the same
// transaction id. (Note that the rand top level functions "use a default
// shared Source that produces a deterministic sequence of values each time a
// program is run" (and we don't seed the shared Source to avoid changing
// customer apps' behavior)).
func RandUint64() uint64 {
seededRand.Lock()
defer seededRand.Unlock()
u1 := seededRand.Uint32()
u2 := seededRand.Uint32()
return (uint64(u1) << 32) | uint64(u2)
}
// RandUint32 returns a random uint32.
func RandUint32() uint32 {
seededRand.Lock()
defer seededRand.Unlock()
return seededRand.Uint32()
}
// RandFloat32 returns a random float32 between 0.0 and 1.0.
func RandFloat32() float32 {
seededRand.Lock()
defer seededRand.Unlock()
for {
if r := seededRand.Float32(); 0.0 != r {
return r
}
}
}
// RandUint64N returns a random int64 that's
// between 0 and the passed in max, non-inclusive
func RandUint64N(max uint64) uint64 {
return RandUint64() % max
}
|