2022-05-19 19:56:03 +00:00
|
|
|
## Nim-Codex
|
2021-02-26 00:23:22 +00:00
|
|
|
## Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2022-04-05 14:24:39 +00:00
|
|
|
import pkg/upraises
|
|
|
|
|
|
|
|
push: {.upraises: [].}
|
|
|
|
|
2021-02-26 00:23:22 +00:00
|
|
|
import pkg/libp2p/crypto/crypto
|
2022-09-14 00:13:16 +00:00
|
|
|
import pkg/bearssl/rand
|
2021-02-26 00:23:22 +00:00
|
|
|
|
|
|
|
type
|
2022-04-05 14:24:39 +00:00
|
|
|
RngSampleError = object of CatchableError
|
2022-09-14 00:13:16 +00:00
|
|
|
Rng* = ref HmacDrbgContext
|
2021-02-26 00:23:22 +00:00
|
|
|
|
|
|
|
var rng {.threadvar.}: Rng
|
|
|
|
|
|
|
|
proc instance*(t: type Rng): Rng =
|
|
|
|
if rng.isNil:
|
|
|
|
rng = newRng()
|
|
|
|
rng
|
|
|
|
|
2022-09-14 00:13:16 +00:00
|
|
|
# Random helpers: similar as in stdlib, but with HmacDrbgContext rng
|
2021-02-26 00:23:22 +00:00
|
|
|
# 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
|
|
|
|
|
|
|
|
while true:
|
2022-09-14 00:13:16 +00:00
|
|
|
let x = rng[].generate(uint64)
|
2021-02-26 00:23:22 +00:00
|
|
|
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)]
|
|
|
|
|
2022-04-05 14:24:39 +00:00
|
|
|
proc sample*[T](
|
|
|
|
rng: Rng, sample, exclude: openArray[T]): T
|
|
|
|
{.raises: [Defect, RngSampleError].} =
|
|
|
|
if sample == exclude:
|
|
|
|
raise newException(RngSampleError, "Sample and exclude arrays are the same!")
|
|
|
|
|
|
|
|
while true:
|
|
|
|
result = rng.sample(sample)
|
|
|
|
if exclude.find(result) != -1:
|
|
|
|
continue
|
|
|
|
|
|
|
|
break
|
|
|
|
|
2021-02-26 00:23:22 +00:00
|
|
|
proc shuffle*[T](rng: Rng, a: var openArray[T]) =
|
|
|
|
for i in countdown(a.high, 1):
|
|
|
|
let j = rng.rand(i)
|
|
|
|
swap(a[i], a[j])
|