mirror of
https://github.com/logos-storage/logos-storage-nim-dht.git
synced 2026-07-29 10:43:17 +00:00
18 lines
515 B
Nim
18 lines
515 B
Nim
from libp2p/crypto/crypto import Rng, generate
|
|
|
|
## Random helpers: similar as in stdlib, but with libp2p Rng
|
|
# TODO: Move these somewhere else?
|
|
const randMax = 18_446_744_073_709_551_615'u64
|
|
|
|
proc rand*(rng: Rng, max: Natural): int =
|
|
if max == 0: return 0
|
|
|
|
var x: uint64
|
|
while true:
|
|
rng.generate(x)
|
|
if x < randMax - (randMax mod (uint64(max) + 1'u64)): # against modulo bias
|
|
return int(x mod (uint64(max) + 1'u64))
|
|
|
|
proc sample*[T](rng: Rng, a: openArray[T]): T =
|
|
result = a[rng.rand(a.high)]
|