forked from sethvargo/go-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
backoff: remove global rand.Seed and using locked rand.Rand (sethvarg…
- Loading branch information
Showing
2 changed files
with
54 additions
and
6 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package retry | ||
|
||
import ( | ||
"math/rand" | ||
"sync" | ||
) | ||
|
||
type lockedSource struct { | ||
src *rand.Rand | ||
lk sync.Mutex | ||
} | ||
|
||
var _ rand.Source64 = (*lockedSource)(nil) | ||
|
||
// Int63 mimics math/rand.(*Rand).Int63 with mutex locked. | ||
func (r *lockedSource) Int63() int64 { | ||
r.lk.Lock() | ||
defer r.lk.Unlock() | ||
return r.src.Int63() | ||
} | ||
|
||
// Seed mimics math/rand.(*Rand).Seed with mutex locked. | ||
func (r *lockedSource) Seed(seed int64) { | ||
r.lk.Lock() | ||
defer r.lk.Unlock() | ||
r.src.Seed(seed) | ||
} | ||
|
||
// Uint64 mimics math/rand.(*Rand).Uint64 with mutex locked. | ||
func (r *lockedSource) Uint64() uint64 { | ||
r.lk.Lock() | ||
defer r.lk.Unlock() | ||
return r.src.Uint64() | ||
} | ||
|
||
// Int63n mimics math/rand.(*Rand).Int63n with mutex locked. | ||
func (r *lockedSource) Int63n(n int64) int64 { | ||
if n <= 0 { | ||
panic("invalid argument to Int63n") | ||
} | ||
if n&(n-1) == 0 { // n is power of two, can mask | ||
return r.Int63() & (n - 1) | ||
} | ||
max := int64((1 << 63) - 1 - (1<<63)%uint64(n)) | ||
v := r.Int63() | ||
for v > max { | ||
v = r.Int63() | ||
} | ||
return v % n | ||
} |