From 8ef8cfcd740f91d0981312668a5bf67281c035ba Mon Sep 17 00:00:00 2001 From: Dmitriy Ryajov Date: Tue, 5 Apr 2022 08:24:39 -0600 Subject: [PATCH] add sample proc with exclude array (#68) --- dagger/rng.nim | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/dagger/rng.nim b/dagger/rng.nim index 276d3717..61ff24aa 100644 --- a/dagger/rng.nim +++ b/dagger/rng.nim @@ -7,10 +7,15 @@ ## This file may not be copied, modified, or distributed except according to ## those terms. +import pkg/upraises + +push: {.upraises: [].} + import pkg/libp2p/crypto/crypto import pkg/bearssl type + RngSampleError = object of CatchableError Rng* = ref BrHmacDrbgContext var rng {.threadvar.}: Rng @@ -36,6 +41,19 @@ proc rand*(rng: Rng, max: Natural): int = proc sample*[T](rng: Rng, a: openArray[T]): T = result = a[rng.rand(a.high)] +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 + proc shuffle*[T](rng: Rng, a: var openArray[T]) = for i in countdown(a.high, 1): let j = rng.rand(i)